问:
Is it possible to have pointers recursively point into themselves?
I have been learning C++ recently, and upon reading up on pointers I had a moment of thought.

I'm still attempting to grasp the very idea of pointers so excuse me if this doesn't make sense beyond comprehension.

Is it possible for a set of pointers recursively point into one another's memory location upon trying to print out the value of what they point at.

This should be done without needing to create this in a "fake" way of creating them in a never ending loop.

It should indefinitely point into infinity when trying to access a pointer's pointed at value. Is this a feasible "thing" to create?

答:
That's not how pointers work.

A pointer is, essentially, a record of a memory address. If dereferenced, you can read (or write) the value that lives at that address.

Pointers can point to anything that lives in memory. In particular, they can point to other pointers. They can even point themselves (although that is pretty useless).

However, the action of dereferencing a pointer must be taken explicitly. A pointer that points to another pointer yields the value of that other pointer when you dereference it, not automatically. And if that other pointer points to a third thing, reaching that third thing takes two explicit actions.

A pointer doesn't magically turn into the thing pointed to in your hands. Therefore it isn't possible to create reference structures that compute forever without having an explicit loop in the mix. Such a loop can run endlessly, like any loop with an insufficient termination condition, but you do need the loop, not just the pointers.


问:
Using a license without a year value
I have this project that has several license notes (all GNU GPLv3) on the top of the source files.

They are all following the "rule" that the year in the copyright notice should be the year on which the file was last modified.

I wonder if I can substitute

Copyright (C) 201X Bernardo Sulzbach

by

Copyright (C) Bernardo Sulzbach

on all the licenses to alleviate the maintenance burden.

答:
No, you can not leave out the year in a copyright notice. The format of a copyright notice is fairly rigidly specified and if you deviate from that, the notice might not be accepted as a valid copyright notice.

From UK Copyright Service fact sheet:

What does a notice consist of?

"Copyright"

  Some countries will not accept the symbol alone, they also require the word "Copyright" to appear in order to consider the notice valid. Using the word ensures that there can be no confusion.

"©"

  The normally recognised symbol. Most countries across the world accept this as the correct manner of displaying copyright.

Year of publication

  In case of a dispute of ownership of a work, the date plays an important part. If your work was developed and published before any potential opponents then you can usually expect to win any case which challenges your rights.

In the case of work which is continually updated, (for example a web site), the year of publication may be shown as a period from first publication until the most recent update, (i.e. 2000-2015)

Copyright owner’s name

  This may only be one person, or it may be a collective, a band, group or team for example.

If there is one person who owns the rights to a work, then his/her name will appear on its own. If however, your work is owned by several people then you may choose to include the name of each member of the collective, or include the name of the collective itself.

This would give your copyright notice the following appearance: Copyright © 2015 Bobby Smith.

ContentLicense: CC BY-SA 3.0

Title: Using a license without a year value


问:
node.js C++ addons to do all major computations
A major limitation of node.js is its single threaded execution and the fact that JS is slow with computations.

What are the advantages/drawbacks of using C++ to do the application's heavy lifting while using node as "glue code"? Obviously there are security risks using C++, but let's assume for the sake of argument that the C++ code is well-tested and perfect.

答:
I do not exactly know what you mean by security risks, with the need to typecheck passed parameters using the is* methods on arguments or obtaining the value representation using the v8::Value, the passed arguments are quite safe to work with.

If you are afraid of manual memory management and consider that a risk (which is not even that scary anymore, with std::move and RAII), then perhaps C++ module is not the way to go, until you learn to do so properly.

But to the question. The main advantage is, it is C++, and as you have already kind of mentioned, well written C++ code will reward you with sheer speed.

I have only tried the Node.js C++ addons for very simple data operations, so I cannot speak for an enterprise-size application, but from the experience I have had, the development is pretty straightforward and fairly easy to implement.

The main disadvantage? It is C++. C++ is by no mean an easy programming language. Although the new standards make it more and more developer friendly, it is still very complicated.

Other than that, there is not really an issue with gluing the two codebases (JavaScript and C++) together and if you know C++, just go ahead and try it for yourself.


答:
For this answer, I'll assume that the C++ code is ONLY well-tested and perfect security wise. If if would be actually be perfect then you wouldn't have asked this question anyways...

This is a general compilation of the first things that came to my head, not a complete list.

technical disadvantages of using C++:

(or basically any external language addon)

Communication:
You will have to deal with any communication happening between your nodeapp and the C++-Code on your own. Any results will probably have to go through some sort of dispatcher in node, which can be problematic, if the message types are very heterogenous.

Interoperability:
There is a good chance, you will run in os-compatibility problems when using c++. Since C++ has to be compiled, there is a good chance, that after optimizing your build process for a certain operating system, you will have a hard time migrating it to another. This could especially be problematic if you are not hosting your own server, but use PaaS Provider.

A bigger code base:
Maintenance and Debugging can (bad code-style can make this even harder) become way more painful, if the code-base stretches over more (and maybe even distributed) systems.

social disadvantages:

You have a split code base and will either have to hire developers which are able to develop good javascript AND C++ code (which could prove to be problematic) or hire separate developers, which is more expensive and one developer can not as easily step in for another if he/she is absent.

technical advantages:

A wider range of libraries. You are not confined to node/js-libraries anymore, but can use all C++ libraries now, too. There are many libraries, which have no equal in js. Especially complex math- or scientific-libraries in general, are very hard to implement in js, due to the underlying language.

Faster computation itself. Unless there is a major overhead in management and communication with C++, there is a good chance, that computational intensive use-cases can benefit from C++.

Since C-Languages are closer to the hardware than higher-abstracted systems like js or node, you can in most cases optimize your software better for the task at hand.

As you can better optimize, you can also use more advanced parallelization. This could either be local computing or even massive HPC (e.g. with OpenMP, MPI...). A framework for scientifical computation would be interesting for this.

social advantages:

since node and C++ are not tightly coupled, you can outsource the C++ development to another, more specialized company and just provide them with the necessary interfaces. (you should, of course have these in place anyways, but there is a good chance that your average code base is not as modular as you want it to be :-))

Finding and hiring specialized people could be easier. Even though it can be hard to find developers who are adept with node AND scientific computing in C++, its probably easier to find specialized people, who are for example very good at parallelization or statistical computation in C++ (or any other, more specialized language like R)

Again, this is not a complete list, just a few things that came to my head. Also, this is not really C++ specific, but rather generic, for any external addon.

Title: node.js C++ addons to do all major computations

Body:
A major limitation of node.js is its single threaded execution and the fact that JS is slow with computations.

What are the advantages/drawbacks of using C++ to do the application's heavy lifting while using node as "glue code"? Obviously there are security risks using C++, but let's assume for the sake of argument that the C++ code is well-tested and perfect.


答:
A very schematic explanation

Basic Idea:
A pointer is a variable storing a memory address (typically 4 bytes)

E.g.

```<code>char* t_pointer; // This Pointer is a 4 bytes variable that will contain (but currently does not contain) the memory address of a char
</code>```

Setting up a pointer value:
A typical way consists of using the “&” address-of or reference operator applied to a variable

E.g.

```<code>char t_char = ‘a’; // A 1 byte variable containing character `a`
char* t_pointer = &t_char; // The pointer now contains the memory address of the `t_char` variable
</code>```

Getting the value of the pointed element:
The “*” dereference operator is used so the syntax (*t_pointer) returns the content of the memory address stored in t_pointer

Two observations:

there is no restriction about the memory address the pointer can store so it can point to a valid memory region, even itself, as well as an invalid memory region
Using the dereference operator involves trying to access that memory region and that’s where issues can happen

C and C++ are typed languages so you should understand what’s the type of the value accessed by the dereference operator
In the above example, the t_pointer is defined as a (char*) so it means that when you dereference it you get char … this means that while dereferencing you are basically reading one byte only as sizeof(char) is 1
In case of int* t_pointer then dereferencing it would caused reading sizeof(int) that’s typically 4 bytes

Finally consider that you are not strongly constrained by the pointer type as you can perform casting

E.g.

```<code>void* t_pointer; // Pointer to an undefined type
int t_int = 11; // Int Variable
t_pointer = &t_int; // Memory address of the first byte of the int
</code>```

variable
    int t_res = (int)(*t_pointer); // Dereference the pointer specifying to read an int and store that value in a new variable

Title: Is it possible to have pointers recursively point into themselves?

Body:
I have been learning C++ recently, and upon reading up on pointers I had a moment of thought.

I'm still attempting to grasp the very idea of pointers so excuse me if this doesn't make sense beyond comprehension.

Is it possible for a set of pointers recursively point into one another's memory location upon trying to print out the value of what they point at.

This should be done without needing to create this in a "fake" way of creating them in a never ending loop.

It should indefinitely point into infinity when trying to access a pointer's pointed at value. Is this a feasible "thing" to create?

Body:
A very schematic explanation

Basic Idea:
A pointer is a variable storing a memory address (typically 4 bytes)

E.g.

char* t_pointer; // This Pointer is a 4 bytes variable that will contain (but currently does not contain) the memory address of a char

Setting up a pointer value:
A typical way consists of using the “&” address-of or reference operator applied to a variable

E.g.

char t_char = ‘a’; // A 1 byte variable containing character `a`
char* t_pointer = &t_char; // The pointer now contains the memory address of the `t_char` variable

Getting the value of the pointed element:
The “*” dereference operator is used so the syntax (*t_pointer) returns the content of the memory address stored in t_pointer

Two observations:

there is no restriction about the memory address the pointer can store so it can point to a valid memory region, even itself, as well as an invalid memory region
Using the dereference operator involves trying to access that memory region and that’s where issues can happen

C and C++ are typed languages so you should understand what’s the type of the value accessed by the dereference operator
In the above example, the t_pointer is defined as a (char*) so it means that when you dereference it you get char … this means that while dereferencing you are basically reading one byte only as sizeof(char) is 1
In case of int* t_pointer then dereferencing it would caused reading sizeof(int) that’s typically 4 bytes

Finally consider that you are not strongly constrained by the pointer type as you can perform casting

E.g.

void* t_pointer; // Pointer to an undefined type
int t_int = 11; // Int Variable
t_pointer = &t_int; // Memory address of the first byte of the int

variable
    int t_res = (int)(*t_pointer); // Dereference the pointer specifying to read an int and store that value in a new variable


问:
If I use locks, can my algorithm still be lock-free?
A common definition of lock-free is that at least one process makes progress. 1

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

1 See eg M. Herlihy, V. Luchangco, and M. Moir. Obstruction-free synchronization: Double-ended queues as an example. In Distributed Computing, 2003. "It is lock-free if it ensures only that some thread always makes progress".

答:
I've studied The Art of Multiprocessor Programming1 and their text is lacking in clarity, just like the book you refer to. Here are some quotes from TAMPP:

Quote 1 (Definition of lock-free)

A method is lock-free if it guarantees that infinitely often some method call finishes in a finite number of steps.

Quote 2 (Definition of nonblocking)

a pending invocation of a total method is never required to wait for another pending invocation to complete.

Quote 3 (claim that lock-free is nonblocking)

The wait-free and lock-free nonblocking progress conditions guarantee that the computation as a whole makes progress, independently of how the system schedules threads.

The problem is that the claim in Quote 3 does not obviously follow from the definition in Quote 1. As already mentioned, a synchronized queue seems to satisfy Quote 1: infinitely often some method will successfully acquire the lock and complete.

Note specifically the quite vague phrase in Quote 3: "independently of how the system schedules threads". This is not preceded by any kind of a formal description of the "thread-scheduling system", so we are left to reconstruct its properties based on our preconceptions on what the definitions should mean:

the system always executes instructions of some thread;

it may never execute instructions of any given thread;

all the threads are invoking the method under consideration.

On such a system, a blocking method cannot be lock-free: if the thread holding the lock is never again scheduled for execution, there will be no other thread which can complete its method invocation in a finite number of steps, yet there will be some threads that are executing steps of the method. For a more realistic system, one which does guarantee to give CPU time to each thread eventually, the definition must explicitly include the nonblocking property:

Corrected definition of lock-free

A method is lock-free if it is non-blocking and, additionally, guarantees that infinitely often some method call finishes in a finite number of steps.

1 Maurice Herlihy, Nir Shavit, The Art of Multiprocessor Programming, Elsevier 2008, pp. 58-60


问:
Is it a good practice to use List of Enums?
I am currently working on a system where there are Users, and each user have one or multiple roles. Is it a good practice to use List of Enum values on User? I can't think of anything better, but this doesn't feel alright.</p>

```<code>enum Role{
  Admin = 1,
  User = 2,
}

class User{
   ...
   List<Role> Roles {get;set;}
}
</code>```

答:
Why not to use Set? If using List:

It is easy to add the same role twice

Naive compare of lists won't work here properly: [User, Admin] is not the same as [Admin, User]

Complex operations such as intersect and merge are not straightforward to implement

If you are concerned about performance, then, for example in Java, there is EnumSet which is implemented as fixed length array of booleans (i'th boolean element answers the question whether i'th Enum value is present in this set or not). For example, EnumSet<Role>. Also, see EnumMap. I suspect that C# has something similar.


答:
Write your enum so you can combine them. By using base 2 exponential you can combine them all in one enum, have 1 property and can check for them. Your enum should be lile this</p>

```<code>enum MyEnum
{
    FIRST_CHOICE = 2,
    SECOND_CHOICE = 4,
    THIRD_CHOICE = 8
}
</code>```

Title: Is it a good practice to use List of Enums?

Body:
I am currently working on a system where there are Users, and each user have one or multiple roles. Is it a good practice to use List of Enum values on User? I can't think of anything better, but this doesn't feel alright.</p>

```<code>enum Role{
  Admin = 1,
  User = 2,
}

class User{
   ...
   List<Role> Roles {get;set;}
}
</code>```

Body:
Write your enum so you can combine them. By using base 2 exponential you can combine them all in one enum, have 1 property and can check for them. Your enum should be lile this

enum MyEnum
{
    FIRST_CHOICE = 2,
    SECOND_CHOICE = 4,
    THIRD_CHOICE = 8
}


答:
That isn't something I've seen but I see no reason why it wouldn't work. You might want to use sorted list so it defends against dupes however.

A more common approach is a single user level e.g. system, admin, power user, user etc. System can do everything, admin most things and so on down.

If you were to set the values of roles as powers of two, you could store the role as an int and derive the roles if you really wanted to store them in a single field but that might not be to everyone's taste.

So you might have:

```<code>Back office role 1
Front office role 2
Warehouse role 4
Systems role 8
</code>```

So if a user had a role value of 6 then they'd have the Front office and Warehouse roles.

Body:
That isn't something I've seen but I see no reason why it wouldn't work. You might want to use sorted list so it defends against dupes however.

A more common approach is a single user level e.g. system, admin, power user, user etc. System can do everything, admin most things and so on down.

If you were to set the values of roles as powers of two, you could store the role as an int and derive the roles if you really wanted to store them in a single field but that might not be to everyone's taste.

So you might have:

Back office role 1
Front office role 2
Warehouse role 4
Systems role 8

So if a user had a role value of 6 then they'd have the Front office and Warehouse roles.


答: The simplistic example you give is fine, but typically it's more complicated than that. For instance, if you are going to persist the users and roles in a database, then you should define the roles in a database table rather than use enums. That gives you referential integrity. </p>


答:
Use HashSet as it prevents duplicates and has more comparison methods

Otherwise good use of Enum

Add a method Boolean IsInRole(Role R)

and I would skip the set

```<code>List<Role> roles = new List<Role>();
Public List<Role> Roles { get {return roles;} }
</code>```

Body:
Use HashSet as it prevents duplicates and has more comparison methods

Otherwise good use of Enum

Add a method Boolean IsInRole(Role R)

and I would skip the set

List<Role> roles = new List<Role>();
Public List<Role> Roles { get {return roles;} }


答:
TL;DR: It is usually a bad idea to use a collection of enums as it often leads to a bad design. A collection of enums usually calls for distinct system entities with specific logic.

It is necessary to distinguish between a few use cases of enum. This list is only of top of my head so there might be more cases...

The examples are all in C#, I guess your language of choice will have similar constructs or it would be possible for you to implement them yourself.

1. Only single value is valid

In this case, the values are exclusive, e.g.

public enum WorkStates
{
    Init,
    Pending,
    Done
}
```

<p>It is invalid to have some work that is both <code>Pending</code> and <code>Done</code>. Therefore only one of these values is valid. This is a good use-case of enum.</p>

<p><strong>2. A combination of values is valid</strong><br>
This case is also called flags, C# provides <code>[Flags]</code> enum attribute to working with these. The idea can be modeled as a set of <code>bool</code>s or <code>bit</code>s with each corresponding to one enum member. Each member should have a value of power of two. Combinations can be created using bitwise operators:</p>

<pre class="lang-cs prettyprint-override"><code>[Flags]
public enum Flags
{
    None = 0,
    Flag0 = 1, // 0x01, 1 << 0
    Flag1 = 2, // 0x02, 1 << 1
    Flag2 = 4, // 0x04, 1 << 2
    Flag3 = 8, // 0x08, 1 << 3
    Flag4 = 16, // 0x10, 1 << 4

    AFrequentlyUsedMask = Flag1 | Flag2 | Flag4,
    All = ~0 // bitwise negation of zero is all ones
}
</code>```

Using a collection of enum members is an overkill in such a case as each enum member only represents one bit that is either set or unset. I guess most of languages support constructs like this. Otherwise you can create one (e.g. use bool[] and address it by (1 << (int)YourEnum.SomeMember) - 1).

a) All combinations are valid

While these are ok in some simple cases, a collection of objects may be more appropriate as you often need additional information or behaviour based on the type.

[Flags]
public enum Flavors
{
    Strawberry = 1,
    Vanilla = 2,
    Chocolate = 4
}

public class IceCream
{
    private Flavors _scoopFlavors;

    public IceCream(Flavors scoopFlavors)
    {
        _scoopFlavors = scoopFlavors
    }

    public bool HasFlavor(Flavors flavor)
    {
        return _scoopFlavors.HasFlag(flavor);
    }
}
```

<p>(note: this assumes you only really care about the flavors of the ice-cream - that you don't need to model the ice-cream as a collection of scoops and a cone)</p>

<p><strong>b) Some combinations of values are valid and some not</strong>  </p>

<p>This is a frequent scenario. The case might often be that you're putting two different things into one enum. Example:</p>

<pre class="lang-cs prettyprint-override"><code>[Flags]
public enum Parts
{
    Wheel = 1,
    Window = 2,
    Door = 4,
}

public class Building
{
    public Parts parts { get; set; }
}

public class Vehicle
{
    public Parts parts { get; set; }
}
</code>```

Now while it's completely valid for both Vehicle and Building to have Doors and Windows, it's not very usual for Buildings to have Wheels.

In this case, it would be better to break up the enum into parts and/or modify the object hierarchy in order to achieve either case #1 or #2a).

Design considerations

Somehow, the enums tend not to be the driving elements in OO since the type of an entity can be considered similar to the information that is usually provided by an enum.

Take e.g. the IceCream sample from #2, the IceCream entity would instead of flags have a collection of Scoop objects.

The less purist approach would be for the Scoop to have a Flavor property. The purist approach would be for the Scoop to be an abstract base class for VanillaScoop, ChocolateScoop, ... classes instead.

The bottom line is that:

1. Not everything that is a "type of something" needs to be enum

2. When some enum member is not a valid flag in some scenario, consider splitting the enum into multiple distinct enums.

Now for your example (slightly changed):

public enum Role
{
    User,
    Admin
}

public class User
{
    public List<Role> Roles { get; set; }
}
```

<p>I think this exact case should be modeled as (note: not really extensible!):</p>

<pre class="lang-cs prettyprint-override"><code>public class User
{
    public bool IsAdmin { get; set; }
}
</code>```

In other words - it is implicit, that the User is a User, the additional info is whether he is an Admin.

If you get to have multiple roles that are not exclusive (e.g. User can be Admin, Moderator, VIP, ... at the same time), that would be a good time to use either flags enum or an abtract base class or interface.

Using a class to represent a Role leads to a better separation of responsibilities where a Role can have the responsibility to decide whether it can do a given action.

With an enum you'd need to have the logic in one place for all the roles. Which defeats the purpose of OO and brings you back to imperative.

Imagine that a Moderator has edit rights and Admin has both edit and delete rights.

Enum approach (called Permissions in order not to mix roles and permissions):

[Flags]
public enum Permissions
{
    None = 0
    CanEdit = 1,
    CanDelete = 2,

    ModeratorPermissions = CanEdit,
    AdminPermissions = ModeratorPermissions | CanDelete
}

public class User
{
    private Permissions _permissions;

    public bool CanExecute(IAction action)
    {
        if (action.Type == ActionType.Edit && _permissions.HasFlag(Permissions.CanEdit))
        {
            return true;
        }

        if (action.Type == ActionType.Delete && _permissions.HasFlag(Permissions.CanDelete))
        {
            return true;
        }

        return false;
    }
}
```

<p>Class approach (this is far from perfect, ideally, you'd want the <code>IAction</code> in a visitor pattern but this post is enormous already...):</p>

<pre class="lang-cs prettyprint-override"><code>public interface IRole
{
    bool CanExecute(IAction action);
}

public class ModeratorRole : IRole
{
    public virtual bool CanExecute(IAction action)
    {
         return action.Type == ActionType.Edit;
    }
}

public class AdminRole : ModeratorRole
{
     public override bool CanExecute(IAction action)
     {
         return base.CanExecute(action) || action.Type == ActionType.Delete;
     }
}

public class User
{
    private List<IRole> _roles;

    public bool CanExecute(IAction action)
    {
        _roles.Any(x => x.CanExecute(action));
    }
}
</code>```

Using an enum may be an acceptable approach though (e.g. performance). The decision here depends on the requirements of the modeled system.

Body:
TL;DR: It is usually a bad idea to use a collection of enums as it often leads to a bad design. A collection of enums usually calls for distinct system entities with specific logic.

It is necessary to distinguish between a few use cases of enum. This list is only of top of my head so there might be more cases...

The examples are all in C#, I guess your language of choice will have similar constructs or it would be possible for you to implement them yourself.

1. Only single value is valid

In this case, the values are exclusive, e.g.

public enum WorkStates
{
    Init,
    Pending,
    Done
}

It is invalid to have some work that is both Pending and Done. Therefore only one of these values is valid. This is a good use-case of enum.

2. A combination of values is valid

This case is also called flags, C# provides [Flags] enum attribute to working with these. The idea can be modeled as a set of bools or bits with each corresponding to one enum member. Each member should have a value of power of two. Combinations can be created using bitwise operators:

[Flags]
public enum Flags
{
    None = 0,
    Flag0 = 1, // 0x01, 1 << 0
    Flag1 = 2, // 0x02, 1 << 1
    Flag2 = 4, // 0x04, 1 << 2
    Flag3 = 8, // 0x08, 1 << 3
    Flag4 = 16, // 0x10, 1 << 4

    AFrequentlyUsedMask = Flag1 | Flag2 | Flag4,
    All = ~0 // bitwise negation of zero is all ones
}

Using a collection of enum members is an overkill in such a case as each enum member only represents one bit that is either set or unset. I guess most of languages support constructs like this. Otherwise you can create one (e.g. use bool[] and address it by (1 << (int)YourEnum.SomeMember) - 1).

a) All combinations are valid

While these are ok in some simple cases, a collection of objects may be more appropriate as you often need additional information or behaviour based on the type.

[Flags]
public enum Flavors
{
    Strawberry = 1,
    Vanilla = 2,
    Chocolate = 4
}

public class IceCream
{
    private Flavors _scoopFlavors;

    public IceCream(Flavors scoopFlavors)
    {
        _scoopFlavors = scoopFlavors
    }

    public bool HasFlavor(Flavors flavor)
    {
        return _scoopFlavors.HasFlag(flavor);
    }
}

(note: this assumes you only really care about the flavors of the ice-cream - that you don't need to model the ice-cream as a collection of scoops and a cone)

b) Some combinations of values are valid and some not

This is a frequent scenario. The case might often be that you're putting two different things into one enum. Example:

[Flags]
public enum Parts
{
    Wheel = 1,
    Window = 2,
    Door = 4,
}

public class Building
{
    public Parts parts { get; set; }
}

public class Vehicle
{
    public Parts parts { get; set; }
}

Now while it's completely valid for both Vehicle and Building to have Doors and Windows, it's not very usual for Buildings to have Wheels.

In this case, it would be better to break up the enum into parts and/or modify the object hierarchy in order to achieve either case #1 or #2a).

Design considerations

Somehow, the enums tend not to be the driving elements in OO since the type of an entity can be considered similar to the information that is usually provided by an enum.

Take e.g. the IceCream sample from #2, the IceCream entity would instead of flags have a collection of Scoop objects.

The less purist approach would be for the Scoop to have a Flavor property. The purist approach would be for the Scoop to be an abstract base class for VanillaScoop, ChocolateScoop, ... classes instead.

The bottom line is that:

1. Not everything that is a "type of something" needs to be enum

2. When some enum member is not a valid flag in some scenario, consider splitting the enum into multiple distinct enums.

Now for your example (slightly changed):

public enum Role
{
    User,
    Admin
}

public class User
{
    public List<Role> Roles { get; set; }
}

I think this exact case should be modeled as (note: not really extensible!):

public class User
{
    public bool IsAdmin { get; set; }
}

In other words - it is implicit, that the User is a User, the additional info is whether he is an Admin.

If you get to have multiple roles that are not exclusive (e.g. User can be Admin, Moderator, VIP, ... at the same time), that would be a good time to use either flags enum or an abtract base class or interface.

Using a class to represent a Role leads to a better separation of responsibilities where a Role can have the responsibility to decide whether it can do a given action.

With an enum you'd need to have the logic in one place for all the roles. Which defeats the purpose of OO and brings you back to imperative.

Imagine that a Moderator has edit rights and Admin has both edit and delete rights.

Enum approach (called Permissions in order not to mix roles and permissions):

[Flags]
public enum Permissions
{
    None = 0
    CanEdit = 1,
    CanDelete = 2,

    ModeratorPermissions = CanEdit,
    AdminPermissions = ModeratorPermissions | CanDelete
}

public class User
{
    private Permissions _permissions;

    public bool CanExecute(IAction action)
    {
        if (action.Type == ActionType.Edit && _permissions.HasFlag(Permissions.CanEdit))
        {
            return true;
        }

        if (action.Type == ActionType.Delete && _permissions.HasFlag(Permissions.CanDelete))
        {
            return true;
        }

        return false;
    }
}

Class approach (this is far from perfect, ideally, you'd want the IAction in a visitor pattern but this post is enormous already...):

public interface IRole
{
    bool CanExecute(IAction action);
}

public class ModeratorRole : IRole
{
    public virtual bool CanExecute(IAction action)
    {
         return action.Type == ActionType.Edit;
    }
}

public class AdminRole : ModeratorRole
{
     public override bool CanExecute(IAction action)
     {
         return base.CanExecute(action) || action.Type == ActionType.Delete;
     }
}

public class User
{
    private List<IRole> _roles;

    public bool CanExecute(IAction action)
    {
        _roles.Any(x => x.CanExecute(action));
    }
}

Using an enum may be an acceptable approach though (e.g. performance). The decision here depends on the requirements of the modeled system.


问:
Is it good practice to avoid warnings and notices?
I've generally been working with PHP warnings and notices off, since I work on a lot of projects where it's already in live production. Now, if I turn on the warnings and notices on these live production websites, they'll be overloaded with them.

The projects that I work on at home, on local, I usually try to work away ALL warnings and notices. Sometimes, there's no solution to not having a notice, so I'd just have to deal with looking at the notice until I decide to turn them off altogether.

In the end, I don't know whether I'm wasting my time trying to get rid of all warnings and notices, or that I'm actually doing this for the greater good.

Hence my question, is it good practice to avoid warnings and notices altogether, or does it really not matter?

答:
If warnings and notices are coming from your code, most definitely fix it.  From my experience, in 95% it may be benign, but the 5% highlight a real problem that may lead to countless hours spent chasing.

If they are coming from the third-party code that you must use for one reason or the other, you generally don't have much choice.

It's a different question if your legacy codebase is really large, then you can treat legacy code as third-party, but require the new code be warning-free.


问:
Should I notify my colleagues when I find a bug in their code?
If I am assigned a bug, I sometimes check version control to see when it was introduced. Should I notify the developer that introduced the bug, even if I already fixed it? The advantage is that it could help learning but the disadvantage is it could seem like criticism</p>

答:
I think, if you found a bug in some developer's area, the best course of action would be to ask that developer to code review your changes.

This way you are not hurting somebody's ego, you are just doing your job (fixing a bug assigned to you, and making sure you don't break more as a result of the 'fix').

Build a conversation in these terms.

I am assigned to work on Problem X (don't mention it's a bug).

I analyzed the code and I see that the best solution for it is to modify code in the Area Y, which you own.

Can you, please, review my solution that I didn't break something I don't know.

From experience, people react much better if you ask their opinion proactively, than by finding out your changes in their code.


答:
Legal Disclaimer. I'm not an attorney. The following should not be construed as legal advice.

They are all following the "rule" that the year in the copyright notice should be the year on which the file was last modified.

A single date on the notice establishes how far back the claim is made (also), so you shouldn't substitute:

```<code>Copyright (C) 2015 Bernardo Sulzbach
</code>```

by

```<code>Copyright (C) 2016 Bernardo Sulzbach
</code>```

You should let it unchanged (typically your individual copyright will extend from 50 to 100 years beyond your death) or write

```<code>Copyright (C) 2015-2016 Bernardo Sulzbach
</code>```

In the hyphenated form, the first date and the second date serve different purposes:

The last date serves to indicate the latest copyright date for any material in the file

Moreover you should update the copyright year only if you made contributions to the work during that year. So if a file hasn't been updated in a given year, there is no ground to touch the file just to update the year.

For the maintenance burden many editors have a copyright update function. E.g. with emacs you can put:

```<code>(add-hook 'before-save-hook 'copyright-update)
</code>```

in the ~/.emacs init file and have copyright-update be called automatically every time a file is saved.

Title: Using a license without a year value

Body:
I have this project that has several license notes (all GNU GPLv3) on the top of the source files.

They are all following the "rule" that the year in the copyright notice should be the year on which the file was last modified.

I wonder if I can substitute

Copyright (C) 201X Bernardo Sulzbach

by

Copyright (C) Bernardo Sulzbach

on all the licenses to alleviate the maintenance burden.

Body:
Legal Disclaimer. I'm not an attorney. The following should not be construed as legal advice.

They are all following the "rule" that the year in the copyright notice should be the year on which the file was last modified.

A single date on the notice establishes how far back the claim is made (also), so you shouldn't substitute:

Copyright (C) 2015 Bernardo Sulzbach

by

Copyright (C) 2016 Bernardo Sulzbach

You should let it unchanged (typically your individual copyright will extend from 50 to 100 years beyond your death) or write

Copyright (C) 2015-2016 Bernardo Sulzbach

In the hyphenated form, the first date and the second date serve different purposes:

The last date serves to indicate the latest copyright date for any material in the file

Moreover you should update the copyright year only if you made contributions to the work during that year. So if a file hasn't been updated in a given year, there is no ground to touch the file just to update the year.

For the maintenance burden many editors have a copyright update function. E.g. with emacs you can put:

(add-hook 'before-save-hook 'copyright-update)

in the ~/.emacs init file and have copyright-update be called automatically every time a file is saved.


答:
Are you the maintainer of the code? If so fix the bug, document the fix, and don't go pointing fingers to who's "to blame" for it in the first place.

Is someone else the maintainer? What were you doing digging through their code in the first place? Notify them that you found a potential problem and where it's located. Maybe give them hints on how to fix it if you've got some. Don't go pointing fingers and laying blame for the problem.

Did you have no business digging into that code? Shame on you, you were wasting your time doing things that aren't your responsibility and might even be in violation of workplace policies regarding access to documents that aren't required for you to do your job.

Way you wrote your question, you seem to just want to gloat to the people who "made the bug". Which is quite often not even the case. Code changes, something that's correct at some point may not be correct later after code somewhere else changes, causing problems with the input of that original code which causes it to misbehave.

Title: Should I notify my colleagues when I find a bug in their code?

Body: If I am assigned a bug, I sometimes check version control to see when it was introduced. Should I notify the developer that introduced the bug, even if I already fixed it? The advantage is that it could help learning but the disadvantage is it could seem like criticism</p>


答:
It matters. A warning might not break your tests or even show up in the wild for a while -- but it could be a symptom of a looming bug. I currently develop primarily in C#/C++ and have a defined strategy to get rid of and keep warnings out of our code base. Luckily it's not rocket science =).

If the language your working in has the ability to treat warnings as errors and has variable warning levels, I would do the following:

Turn the warning level down just far enough so you don't get any warnings. If you are at the lowest warning level and you still get warnings -- try to fix them. If you can't fix them, then you're done for now, but hopefully you can fix them. Great.

Since you now have no warnings (at a low warning level most likely), flip the switch and treat all warnings as errors.

Try to turn the warning level up and fix all the new warnings. If you can't, turn the warning level back down, but don't turn off treat warnings as errors.

I find that this not only works warnings out of my code -- it keeps them out.

Title: Is it good practice to avoid warnings and notices?

Body:
I've generally been working with PHP warnings and notices off, since I work on a lot of projects where it's already in live production. Now, if I turn on the warnings and notices on these live production websites, they'll be overloaded with them.

The projects that I work on at home, on local, I usually try to work away ALL warnings and notices. Sometimes, there's no solution to not having a notice, so I'd just have to deal with looking at the notice until I decide to turn them off altogether.

In the end, I don't know whether I'm wasting my time trying to get rid of all warnings and notices, or that I'm actually doing this for the greater good.

Hence my question, is it good practice to avoid warnings and notices altogether, or does it really not matter?


答:
At the very least, you should notify them that you have discovered a potential bug with their code. This could be considered criticism (and you must be certainly be constructive when criticizing); but there is also potential that what you have found is not actually a bug.

By notifying the responsible party, you aren't just assigning blame. You are also giving the author an opportunity to defend his actions. It may well be that the "bug" was an intended (or discovered) feature that is relied upon by your users. It is also very possible that, even in the case of a real bug discovered, your solution overlooks corner cases that the code's author is more familiar with.

By notifying a bug's author, you also give them the opportunity to rectify any other similar mistakes they may have made. If they have made a mistake in one place, it is likely that they may have made a similar mistake in others.


问:
Is the purpose behind code being 'idiomatic' to reduce cognitive overhead?
I'm trying to explain to someone that the way they've written the code makes it hard to understand, and if you refactor it then it's easier to read. This style of code I'm driving at is commonly called 'idiomatic' code'.

But the phrase idiomatic code brings with it baggage of moral correctness, which is not a great motivator to get people to change their coding style. A more positive way of saying this is code that follows the common style - but to a critical thinker that comes across as herd mentality reasoning.

The way I've come up with explaining this idea in a way that motivates people to change their code is:

writing the code in such a way that it reduces the cognitive overhead of the reader (eg I can't remember if this is the first kind of vector - or the 5th kind of vector)

code that makes it easier to understand the intent (eg what is this vector for?)

(As an aside, I'm aware the book The Joy of Clojure, prior to its first publishing, had the draft title Idiomatic Clojure. So it would seem a reason for making code 'idiomatic', to 'bring joy' to the reader).

My question is: Is the purpose behind code being 'idiomatic' to reduce cognitive overhead?

答:
Most languages intentionally lend themselves to a particular style. Code written in that style is what is idiomatic. If you look past the circumstantial fact that you choice of runtime environment narrows your available choice of languages, you should choose languages because the problem at hand is easy to express in the particular idioms of a language.

Most people don't get that though. For example, many Java programmers try hard to keep the same style when they have to write JavaScript (they could have written Java and cross-compiled it, mind you) and succeed to some extent - writing code that is Java-idiomatic in JavaScript - but they will always have the feeling of fighting JavaScript. Missing certain features or finding it hard to emulate them.

Idiomatic code is good. It is hard for the outsider, but they can learn. Ultimately, code has to be maintained for years, so if you can find a language within the idioms of which the underlying program can be expressed in plain fashion, that's what you should do.

Let me just clarify that there is definitely such a thing as overuse of idioms (or the underlying language features). If you use C++ templates to execute significant parts of the application logic at compile time, or if your complete Lisp program is a call to some macro that unfolds to the actual thing in practically unpredictable ways, if your Java solution of a simple problem inflates to the proportions of FizzBuzzEnterpriseEdition ... you're doing it wrong.

People say code must be easy to read. That's only half the truth. It must be easy to understand, which requires it to be easy to reason about also. That requires an adequate use of abstractions. As with most things, it's a matter of striking the right balance.


答:
if I turn on the warnings and notices on these live production websites, they'll be overloaded with them.

You should always have warnings turned on to the fullest level in development, testing, and QA, but not in production. Actually, if it's a dogfooding application, i.e. an application that you use yourself, then you should also have them turned on in production.

Basically: have them turned on in those cases where the person who sees them is in a position to do something about them (the developer in development and testing can fix them himself, the tester in QA can file a bug, and if the developer is also the user, then he can also fix it in production), but don't turn them on when the person who sees can't do anything about them (a user in production, who doesn't even know how to program).

Ideally, you'll also want to turn on treating warnings as errors, but that only works if there are none to begin with ;-) But keep this in mind as a goal! If it is possible to turn this on/off on a per-file basis, turn it on for all new files, and turn it on for all warning-free files, and never turn it off again once turned on.

So, what to do about the overload?

You make a list of every warning and notice, and then adhere to the following rules:

Never, ever, under no circumstances add a new warning to the list. Every new piece of code, every edit, every change, every patch, every commit must not introduce new warnings, it may only ever fix them.

Everytime you touch a piece of code, fix any and all warnings in that piece of code. (The Boyscout Rule: always leave the campsite in better condition than you found it.) That way, the un-important code can stay full of warnings, but the important code will get cleaner over time. "Piece of code" may be a function, a class, a file. You may also relax this rule to say to fix at least one warning. The point is: fix them as you find them.

Note: both of these require that you have some sort of log database and log filtering mechanism in place. Note also, that "log database" and "log filtering mechanism" could just be a text file and grep.

This is the important bit. Without the database, you won't know when you add a new warning, and without the filtering, you still have the overload problem.

Note #2: this doesn't only work for warnings, it also works for style checkers, complexity metrics, code coverage, static analysis tools, and so on. Basically:

Don't add new problems.

Fix old problems as you stumble across them.

This allows you to easily prioritize: code that is edited often and thus needs to be easy to read and maintain, will get better over time. Code that isn't touched often, won't get better, but that's okay, because nobody needs to look at it anyway. And, at least it won't get worse.

Of course, nothing stops you from allocating time specifically in order to do nothing but hunt down and kill warnings. It's just that often, this isn't economically viable, and it is your job as an engineer to keep that in mind. "An engineer is one who can build with a dollar, what any fool can build with two."


问:
Handling Multiple Collections in C#
I'm currently trying to learn C# and want to enhance my understanding of Object Oriented Programming (OOP). I'm hoping to accomplish this by experimenting with a small program that keeps track of my school assignments/information. I've constructed classes relating to my Institutions, Semesters(Terms), Courses, and Assignments. My question is whether or not I have created and implemented my classes correctly in regards to the information they represent. My thinking suggests that my classes should not inherit from one another in a parent/child like fashion because they are physically unrelated. However accessing objects through multilevel lists seems impractical (I think).. Is there a better way of doing this that doesn't force me to access object by iterating through collections, but still implements OOP best practices?

Program Source Code

Entry Point / Main

```<code>static void Main(string[] args)
{
    List<Institution> Institutions = new List<Institution>();
    Institutions.Add(new Institution("My college"));
    Institutions[0].AddNewTerm("2016", "Spring");
    Institutions[0].Terms[0].AddNewCourse("Math 210");
    Institutions[0].Terms[0].Courses[0].AddNewAssignment("Chapter 1");
    MessageBox.Show(Institutions[0].Terms[0].Courses[0].Assignments[0].Name);
}
</code>```

Class List

Institution

```<code>class Institution
{
    public string Name { get; set; }
    public List<Term> Terms { get; set; }

    public Institution(string UP_Name)
    {
        this.Name = UP_Name;
        this.Terms = new List<Term>();
    }

    public void AddNewTerm(string NewTermYear, string NewTermSeason)
    {
        Terms.Add(new Term(NewTermYear, NewTermSeason));
    }
}
</code>```

Term

```<code>class Term
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Season { get; set; }
    public List<Course> Courses { get; set; }

    public Term(string NewSeason, string NewYear)
    {
        this.Season = NewSeason;
        this.Year = NewYear;
        this.Courses = new List<Course>();
        this.Name = (this.Season + " " + this.Year);

    }

    public void AddNewCourse(string NewCourseName)
    {
        this.Courses.Add(new Course(NewCourseName));
    }
}
</code>```

Course

```<code>class Course
{
    public string Name { get; set; }

    public List<Assignment> Assignments { get; set; }

    public Course(string UP_Name)
    {
        this.Name = UP_Name;
        this.Assignments = new List<Assignment>();
    }

    public void AddNewAssignment(string NewAssignmentName)
    {
        Assignments.Add(new Assignment(NewAssignmentName));
    }

}
</code>```

Assignment

```<code>class Assignment
{
    public string Name { get; set; }

    public Assignment(string UP_Name)
    {
        this.Name = UP_Name;
    }
}
</code>```

答:
It's not bad for a newbie.  You're right to be concerned about accessing objects through multilevel lists.  Also, hard coding the indexes will hurt you eventually (but it's OK for now).

You might try changing AddNewxxx() to return what was added.  For example, if you change Term's AddNewClass to

```<code>public Course AddNewCourse(string NewCourseName)
{
    Course result = new Course(NewCourseName);
    this.Courses.Add(result);
    return result;
}
</code>```

in your Main() function you'll be able to do something like

```<code>var mathCourse = Institutions[0].Terms[0].AddNewCourse("Math 210");
mathCourse.AddNewAssignment("Chapter 1");
mathCourse.AddNewAssignment("Chapter 2");
</code>```

and so on.

Be patient; there is a lot to learn.

Title: Handling Multiple Collections in C#

Body:
It's not bad for a newbie.  You're right to be concerned about accessing objects through multilevel lists.  Also, hard coding the indexes will hurt you eventually (but it's OK for now).

You might try changing AddNewxxx() to return what was added.  For example, if you change Term's AddNewClass to

public Course AddNewCourse(string NewCourseName)
{
    Course result = new Course(NewCourseName);
    this.Courses.Add(result);
    return result;
}

in your Main() function you'll be able to do something like

var mathCourse = Institutions[0].Terms[0].AddNewCourse("Math 210");
mathCourse.AddNewAssignment("Chapter 1");
mathCourse.AddNewAssignment("Chapter 2");

and so on.

Be patient; there is a lot to learn.


答:
You're right not to use inheritance, and in fact I think your design is fine. Let's take a look at one of your uses of your code.

```<code>MessageBox.Show(Institutions[0].Terms[0].Courses[0].Assignments[0].Name);
</code>```

While the [0] uses here are standard for testing, in most uses of a class-based design, you would not be accessing the lists directly by some index, eg writing the number 0 into your code. Instead, you would have lots of "for-each" loops that are performing some important function on all Terms, and then all Courses in that term. Those operations will also look cleaner when the looping is separated into multiple tabbed {} blocks, rather than all in one line.

One-to-Many object mapping is a very important and common concept in programming in general. Your operating system has many Users (usually just one). Each User can run many Programs simultaneously. Those Programs can run multiple Threads...etc

You won't ever get away from the need to use collections, although programming has evolved to make them easier to use. C# in particular has a mechanism called "LINQ" that lets you quickly create "pretend-collections" that represent all parts of another collection, but changed in some way. That's worth reading up on its own, though.

Response to comment...

That's already how all objects (in C# anyway) work; only by references. Let's look at this example.

```<code>Course course101 = Institutions[0].Terms[0].Courses[5];
Console.Writeline(Institutions[0].Terms[0].Courses[5].Name); // "C# 101"
course101.Name = "Boring Class";
Console.Writeline(Institutions[0].Terms[0].Courses[5].Name); // "Boring Class"
</code>```

The only time you actually have a new, separate object is when you call new Course(). Otherwise, the only things you are passing around as variables are references. So in case you were worried you'd need to pass around "institutionIndex, termIndex, courseIndex" for each function, definitely don't worry about that.

Title: Handling Multiple Collections in C#

Body:
I'm currently trying to learn C# and want to enhance my understanding of Object Oriented Programming (OOP). I'm hoping to accomplish this by experimenting with a small program that keeps track of my school assignments/information. I've constructed classes relating to my Institutions, Semesters(Terms), Courses, and Assignments. My question is whether or not I have created and implemented my classes correctly in regards to the information they represent. My thinking suggests that my classes should not inherit from one another in a parent/child like fashion because they are physically unrelated. However accessing objects through multilevel lists seems impractical (I think).. Is there a better way of doing this that doesn't force me to access object by iterating through collections, but still implements OOP best practices?

Program Source Code

Entry Point / Main

```<code>static void Main(string[] args)
{
    List<Institution> Institutions = new List<Institution>();
    Institutions.Add(new Institution("My college"));
    Institutions[0].AddNewTerm("2016", "Spring");
    Institutions[0].Terms[0].AddNewCourse("Math 210");
    Institutions[0].Terms[0].Courses[0].AddNewAssignment("Chapter 1");
    MessageBox.Show(Institutions[0].Terms[0].Courses[0].Assignments[0].Name);
}
</code>```

Class List

Institution

```<code>class Institution
{
    public string Name { get; set; }
    public List<Term> Terms { get; set; }

    public Institution(string UP_Name)
    {
        this.Name = UP_Name;
        this.Terms = new List<Term>();
    }

    public void AddNewTerm(string NewTermYear, string NewTermSeason)
    {
        Terms.Add(new Term(NewTermYear, NewTermSeason));
    }
}
</code>```

Term

```<code>class Term
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Season { get; set; }
    public List<Course> Courses { get; set; }

    public Term(string NewSeason, string NewYear)
    {
        this.Season = NewSeason;
        this.Year = NewYear;
        this.Courses = new List<Course>();
        this.Name = (this.Season + " " + this.Year);

    }

    public void AddNewCourse(string NewCourseName)
    {
        this.Courses.Add(new Course(NewCourseName));
    }
}
</code>```

Course

```<code>class Course
{
    public string Name { get; set; }

    public List<Assignment> Assignments { get; set; }

    public Course(string UP_Name)
    {
        this.Name = UP_Name;
        this.Assignments = new List<Assignment>();
    }

    public void AddNewAssignment(string NewAssignmentName)
    {
        Assignments.Add(new Assignment(NewAssignmentName));
    }

}
</code>```

Assignment

```<code>class Assignment
{
    public string Name { get; set; }

    public Assignment(string UP_Name)
    {
        this.Name = UP_Name;
    }
}
</code>```

Body:
You're right not to use inheritance, and in fact I think your design is fine. Let's take a look at one of your uses of your code.

MessageBox.Show(Institutions[0].Terms[0].Courses[0].Assignments[0].Name);

While the [0] uses here are standard for testing, in most uses of a class-based design, you would not be accessing the lists directly by some index, eg writing the number 0 into your code. Instead, you would have lots of "for-each" loops that are performing some important function on all Terms, and then all Courses in that term. Those operations will also look cleaner when the looping is separated into multiple tabbed {} blocks, rather than all in one line.

One-to-Many object mapping is a very important and common concept in programming in general. Your operating system has many Users (usually just one). Each User can run many Programs simultaneously. Those Programs can run multiple Threads...etc

You won't ever get away from the need to use collections, although programming has evolved to make them easier to use. C# in particular has a mechanism called "LINQ" that lets you quickly create "pretend-collections" that represent all parts of another collection, but changed in some way. That's worth reading up on its own, though.

Response to comment...

That's already how all objects (in C# anyway) work; only by references. Let's look at this example.

Course course101 = Institutions[0].Terms[0].Courses[5];
Console.Writeline(Institutions[0].Terms[0].Courses[5].Name); // "C# 101"
course101.Name = "Boring Class";
Console.Writeline(Institutions[0].Terms[0].Courses[5].Name); // "Boring Class"

The only time you actually have a new, separate object is when you call new Course(). Otherwise, the only things you are passing around as variables are references. So in case you were worried you'd need to pass around "institutionIndex, termIndex, courseIndex" for each function, definitely don't worry about that.


答:
Is it a good practice to use List of Enum values on User?

Short answer: Yes

Better short answer: Yes, the enum defines something in the domain.

Design-time answer: Make and use classes, structures, etc. that model the domain in terms of the domain itself.

Coding time answer: Here's how to code-sling enums ...

The inferred questions:

Should I use strings?

answer: No.

Should I use some other class?

In addition to, yes. Instead of, no.

Is the Role enum list sufficient for use in User?

I have no idea. It is highly dependent on other design details not in evidence.

WTF Bob?

This is a design question that is framed in programming language technicalities.

An enum is a good way to define "Roles" in your model. So then a List of roles is a good thing.

enum is far superior to strings.

Role is a declaration of ALL roles that exist in the domain.

The string "Admin" is a string with the letters "A" "d" "m" "i" "n", in that order. It is nothing as far as the domain is concerned.

Any classes you might design to give the concept of Role some life - functionality - can make good use of the Role enum.

For example rather than sub-class for every kind of role, have a Role property that tells what kind of role this class-instance is.

A User.Roles list is reasonable when we don't need, or don't want, instantiated role objects.

And when we do need to instantiate a role, the enum is an un-ambiguous, type safe way to communicate that to a RoleFactory class; and, not insignificantly, to the code reader.


问:
User account model with two or three possible profile
My application will have at least two types of users: clients and companies, these are the types of profiles. Because each type of profile requires different additional information, it will be required to create a table for each type of profile.

How should I create my relationships so a user has zero or one client profile, or zero or one company profile, but in a way that he must have one and only one of the two types of profiles?

E.g. John is a client, then he has a row on Users table and UsersProfiles. He can't have a row in CompaniesProfiles at the same time.

答: I think you have two choices: either have one profile reference and an indicator in the user record to identify the profile type, or have two profile references and enforce your requirement using insert and update triggers. In the first case, you'll have to forego referential integrity (since your foreign key can reference two different tables), but you save space by only using one field. In the second case, you maintain referential integrity at the cost of added complexity due to the use of triggers (and possibly more complexity if you need to do bulk inserts, since triggers are often disabled for performance reasons when large amounts of data are inserted).</p>


问:
Simple and Composite transactional services: Question about separation of concerns and transactions
I believe I know the answer to this but I'm looking for any holes or anything I may be missing.

This is focused on Spring and Java but could really apply to any programming stack.

Anyway, we have a typical service layer annotated with @Transactional in Spring.  For example, we could have:

```<code>EmailService
OrderService
HistoryService
</code>```

Now, the user performs an action that calls a RESTful service that does the following:

```<code>orderService.create(....);    // wrapped in @Transactional
historyService.create(....);  // wrapped in @Transactional
emailService.emailUser(....); // wrapped in @Transactional (also annotated with @Async)
</code>```

While all of these are called from a controller (which is NOT @Transactional), if either the order service or the history service fail, I want both to be rolled back and the email service would abort.

I don't like mixing the services.  I think it would be ugly to have the order service call the history service just so that both of them are in the same transaction boundaries.

My first instinct was to create a hybrid service that would wrap both services together.  Something like:

```<code>@Transactional
public void orderEntryService.create(....) {
    orderService.create(....);    // STILL wrapped in @Transactional
    historyService.create(....);  // STILL wrapped in @Transactional
}
</code>```

This way, my controller could be:

```<code>public String create(...) {
    orderEntryService.create(...);

    emailService.emailUser(...);    // this is @Async
                                    // and will never be called if previous
                                    // orderEntryService.create fails
}
</code>```

While I think this keeps my service layer cleaner, it can quickly start adding up to bulky and forgetful "aggregate" service classes. How to handle this?

答:
I do not have a definitive answer but here are my points:

In favor:

I do not like business logic in the controller. They already have a lot of boilerplate code related to the view, format, transformations, bindings, mapping, etc. Three calls with its own error handling (and may be some specials cases) can become complex enough to bring bugs. The logic of how to create an order could be complex enough that that you want it separated from how do you call it.

Controllers are hard to test. Services are easy. You avoid mocking the WebApplicationContext, the json de/serialization, the controller error handling, SpringSecurityFilterChain, etc. You may even have to mock authorization. Of course you will try to test the controller anyway but those are heavier test that focus on the communication between server and client. With locale and input santiation they have enough complexity.

Task that need to be executed transactionally. Lets say that you need to execute two services: shipGoods and chargeCreditCard. shipGoods executes sucessfully and then chargeCreditCard fails. You would like to revert the shipping order. Alternative: You could create a "component" level between DAO and Service when only full business logic is called in services. And you do not want transactionall DAOs.

Allow smaller transactions when you do not need a big one. In the opossite case you may be calling a lot of functionallity like search services or webservices calls. If you do not need to rollback a transaction it is better to commit it as soon as possible. Open transactions can lock database records (or even full tables) reducing performance. Example: update entity in database, call slow remote webservice add create a different entity. In a big transation approach the entity won't be committed until the last creation ends and nobody will be able to update the original record.

Code reuse: It is hard to reuse code without services calling another services. Lets say you have a very tested "chargeCreditCard" method. You may want to reuse it even in cases where "shipGoods" is changed to "preorderItem". If you consider sending an email a service (and it seems so judging by emailService) then it seems that "forgottenPasswordService", "newsLetterService", "shippingService" could really benefit from reusing the funtionality.

Against:

Complex transactions: if you create a big transaction that includes the three services you will have to think about what happens when each one fails. Nothings forbids the creation of a non-transactional service that calls transactional ones. That is the easy case. Nested transactions and autonomous transactions can be powerfull but hard and dangerous.

Complexity: You can end with lots of services calling services calling services. Do you really have a business logic so complex? Beware of creating  services like transactional DAOs with only CRUD operations but hardly any logic: For example: OrderService, HistoryService. In this case you can consider that OrderService should call historyDAO and include histories automatically when you create  an order. (Avoid the Anemic Domain Model Antipattern).


问:
How to optimize iterable queries with external arguments

I will use C# here as an example, but my question is about any language.

My question is from framework to compiler perspective (i.e the solution can be by implementing given idea inside compiler)

Consider such code:

```<code>if (sequence.Any()) ...
</code>```

and let's say the sequence "holds" 1 million items. This condition will be executed pretty fast nevertheless (with single check -- either iterator moves or not). Now, slight change:

```<code>if (sequence.Count() > 1) ...
</code>```

now the sequence will be iterated over 1 million items and after that the result will be "oh yes, we have at least 1 item".

Question: how it could be optimized in such way, that the excessive iterations will not be made. On the other hand I would like to avoid polluting framework with plethora of "optimized" methods -- CountAtMost, CountAtLeast -- and so on.

Of source Count is just example, another aggregation queries come to mind -- consider expression (wrong example I am keeping it for historical reasons) collection.Sum() > 1000.

I am not asking about C#-specific optimizations, the question is completely general -- iterable sequences are present in a lot of languages. Iterable sequences can come from generators as well, so the question is how to optimize aggregation query with external (comparing to query) arguments.

答:
Do you absolutely need these huge collections in your business layer?

Where do these huge collections come from? If for instance, they come from a database, then it might be a good idea to filter/count/sum the result on the database-side of things. This will save loads of processing-power and memory.

Is your program absolutely required to handle these enormous collections?
If not, then try to optimize the sizes of your collections before they enter your business-layer.

Either way...

A somewhat C#-specific answer:

If performance is of enormous concern then you will have to implement some of these methods, if it's just a "one-time"-thing, just use foreach with a local count-variable. However; just calling .Count() on a large collection is not an enormously heavy operation in itself, as long as the enumeration of each item doesn't take enormous amount of processing-power/time, in which case, you should probably be careful of how many items you enumerate (i.e. use Take). So creating methods like these might in the end be considered micro-optimization, that is if the collection will always contain 1 million items or less.

Another way to tackle the problem is to enumerate the IEnumerable<T> to a collection of some sort – List<T>, for example.

This requires just one enumeration, which will yield you information about the collection, such as .Count and indexed access to items within it.

This of course depends on whether or not you are going to perform multiple operations on the collection, since it must be enumerated at least once.

Try to be pragmatic, ask yourself the simple questions. Will I need indexed access to the items? Do I need the count? Do I need to make sure there are at least fifteen items? Will i need to perform multiple enumerations of the collection? Will this collection be enormous? Then simply work from there, there is no magical correct way that always works, you absolutely must do trade-offs.

At one point in the code, it might be a good idea to iterate just 10 items, just to check if it contains 10 items or more, at another place; calling Count() might be a better idea.

At one point in the code, enumerating your collection to a List<T> might be a great idea, at other points – it might not.

Also, C# already has some great built in "i only want X"-items within Linq, for instance Take.

Code example:

```<code>if (hugeCollection.Take(4).Count() == 4)
{
    Foo();
}
</code>```

This will not enumerate the entire collection, just the first 4 items, twice. Which for small collections might not be that great, but for larger collections, sure.

A C# tidbit:

Whether .Any() or .Count() is faster depends on whether the call is being made on an ICollection<T> or not. For ICollection<T>, Microsoft went ahead and optimized it, looking at the .Count-property; which is marginally faster than calling .Any(), regardless of the collections size – since the collection will never have to be enumerated.

Body:
Do you absolutely need these huge collections in your business layer?

Where do these huge collections come from? If for instance, they come from a database, then it might be a good idea to filter/count/sum the result on the database-side of things. This will save loads of processing-power and memory.

Is your program absolutely required to handle these enormous collections?
If not, then try to optimize the sizes of your collections before they enter your business-layer.

Either way...

A somewhat C#-specific answer:

If performance is of enormous concern then you will have to implement some of these methods, if it's just a "one-time"-thing, just use foreach with a local count-variable. However; just calling .Count() on a large collection is not an enormously heavy operation in itself, as long as the enumeration of each item doesn't take enormous amount of processing-power/time, in which case, you should probably be careful of how many items you enumerate (i.e. use Take). So creating methods like these might in the end be considered micro-optimization, that is if the collection will always contain 1 million items or less.

Another way to tackle the problem is to enumerate the IEnumerable<T> to a collection of some sort – List<T>, for example.

This requires just one enumeration, which will yield you information about the collection, such as .Count and indexed access to items within it.

This of course depends on whether or not you are going to perform multiple operations on the collection, since it must be enumerated at least once.

Try to be pragmatic, ask yourself the simple questions. Will I need indexed access to the items? Do I need the count? Do I need to make sure there are at least fifteen items? Will i need to perform multiple enumerations of the collection? Will this collection be enormous? Then simply work from there, there is no magical correct way that always works, you absolutely must do trade-offs.

At one point in the code, it might be a good idea to iterate just 10 items, just to check if it contains 10 items or more, at another place; calling Count() might be a better idea.

At one point in the code, enumerating your collection to a List<T> might be a great idea, at other points – it might not.

Also, C# already has some great built in "i only want X"-items within Linq, for instance Take.

Code example:

if (hugeCollection.Take(4).Count() == 4)
{
    Foo();
}

This will not enumerate the entire collection, just the first 4 items, twice. Which for small collections might not be that great, but for larger collections, sure.

A C# tidbit:

Whether .Any() or .Count() is faster depends on whether the call is being made on an ICollection<T> or not. For ICollection<T>, Microsoft went ahead and optimized it, looking at the .Count-property; which is marginally faster than calling .Any(), regardless of the collections size – since the collection will never have to be enumerated.


问:
Why does integer division result in an integer?
We learned in Intro to Programming that if you divide two integers, you always get an integer. To fix the problem, make at least one of those integers a float.

Why doesn't the compiler understand I want the result to be a decimal number?

答:
Why doesn't the compiler understand I want the result to be a decimal number?

The C++ compiler is simply following well-defined and deterministic rules as set forth in the C++ standard. The C++ standard has these rules because the standards committee decided to make it that way.

They could have written the standard to say that integer math results in floating-point numbers, or does so only in the case of a remainder. However, that adds complexity: I either need to know ahead of time what the result is, or maybe convert back to integer if it always gives a float. Maybe I want an integer.

One of C++'s core philosophies is "you do not pay for what you do not use." If you actually want the complexity of mixing integers and floats (and the extra CPU instructions and memory accesses this entails1), then do the type cast as you mentioned in your question. Otherwise, stick to standard integer math.

Finally, mixing integral and floating point variables can result in loss of precision and sometimes incorrect results as I discuss below. If you want this, then pay for it: otherwise, the standard dictates that compilers stick to a strict set of rules for mixing data types. This is well-defined behavior: as a C++ developer, I can look this up in the standard and see how it works.

There are essentially three ways to do what you are trying to do, each with benefits and drawbacks.

Integer math: this results in truncating results during division as you found out. If you want the decimal portion, you need to treat that separately by dividing, getting the remainder, and treating the decimal portion as the remainder divided by the divisor. This is a bit more complex of an operation and has more variables to juggle.

Floating-point math: this will generally produce correct (enough) results for small values, but can easily introduce errors with precision and rounding, especially as the exponent increases. If you divide a large number by a small number, you may even cause an underflow or simply get a wrong result because the scales of the numbers do not play nicely with each other.

Do your own math. There are classes out there that handle extended precision of decimal and rational numbers. These will typically be slower than math on built-in types, but are generally still pretty quick and provide arbitrary-precision math. Rounding and other issues are not automatic like they are with IEEE floats, but you gain more control and certainly more accuracy.

The key here is to choose based on the problem domain. All three methods of representing numbers have their own benefits and drawbacks. Using a loop counter? Pick an integral type. Representing locations in 3D space? Probably a group of floats. Want to track money? Use a fixed-decimal type.

1 Most popular CPU architectures (e.g. x86-64) will have separate sets of instructions that operate on different register types such as integer and floating point, plus extra instructions to convert between integral, floating point, and various representations of them (signed and unsigned, float and double). Some of these operations may entail memory access as well: convert a value and store it to memory (its variable). Math at the CPU level is not as simple as "integer in, float out." While adding two integers may be a very simple operation, possibly a single instruction, mixing data types can increase the complexity.


答:
This is due to the evolution of hardware. Back in the early days of computers, not all machines had a floating point unit, the hardware was simply not able to understand the notion of a floating point number. Of course, floating point numbers can be implemented as a software abstraction, but that has significant downsides. All of the arithmetic on these machines had to be pure integer arithmetic by default.

And still today, there is a firm distinction between integer and floating point arithmetic units within a CPU. Their operands are stored in separate register files to start with, and an integer unit is wired to take two integer arguments and produce an integer result that ends up in an integer register. Some CPUs even require an integer value to be stored to memory, and then reloaded back into a floating point register, before it can be recoded into a floating point number, before you can perform a floating point division on it.

As such, the decision made by the C developers back in the very beginning of the language (C++ simply inherited this behavior), was the only appropriate decision to make, and remains of value today: If you need floating point math, you can use it. If you don't need it, well you don't have to.

Title: Why does integer division result in an integer?

Body:
We learned in Intro to Programming that if you divide two integers, you always get an integer. To fix the problem, make at least one of those integers a float.

Why doesn't the compiler understand I want the result to be a decimal number?


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
I suggest to start a project on your own on a topic that you're interested in.

A lot can be learned by working on a project in general.  It is not needed to see how someone else codes to learn how to code better.  And sometimes you'll actually see what not to do as the other people are often no more experienced than you are.

It usually helps to see other's code, but you will encounter other people's code in your own project just via the libraries and components you use.

Experience will teach you what is good and bad practice.

ContentLicense: CC BY-SA 2.5


问:
How important are daily builds?
One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?</p>

答:
Need to add a bit to this (and @GoodEnoughs):

but this only sounds like a minor
  nuisance for distributed version
  control.

Emphatically no - what a "server" build does is tell you that your trunk will build and pass its tests more or less from clean (the less is the amount of config you need to do of your environment).

I'm contemplating a switch to DVCS but even having done so you will drag my continuous integration from my cold dead hands.

To take a simple example - you're developing feature "a" he's developing feature "b" distributed or not at some point you need to stitch it all together - if, when you commit, you forget to add a file the app will build on your machine but it won't anywhere else. So when you push the build to your "trunk" the Continuous Integration will trigger and the build will fail and you will know and hopefully before anyone pulls your not quite so complete code you'll be able to take steps.

If you're working on a project with multiple developers you've got to be able to define where release versions come from - the trunk in effect - this is true regardless of how your version control works.

If you've added a feature - especially one on which other people have a dependency - to be able to be confident that when it is pushed to "live" that it builds and passes tests somewhere other than your dev environment is huge. More than that, I deploy from builds from my build server - its kind of how one specifies the "definitive" build. Ultimately I'm going to have user triggered deployment builds. Its no good saying that you can work round it - you can't if you need it (and I have scrambled round dev boxes in an office to find and commit missing files).

Is that all a bit strong? Don't know - but my build server is one of those things that having got I have no wish to give back.

Title: How important are daily builds?


问:
Is there a reason for support multiple different releases?
I have a discussion with my team recently and I heard a suggestion for deploying multiple releases. Such as version (newest) and version (old).
But I am thinking what would be the reason for customer want to use the older version. What if the bug was introduced in the older version we would have to make additional support to it.

I see there are benefits of using older version. Maybe I am wrong but what would be the reason why people want the older releases?? and if the trade off wasnt worth it (support vs demand) then why are we plan to support multiple releases?

答:
Older versions can bring stability to a software deployment.

New versions of software may introduce new bugs, potentially crippling bugs. For anything mission-critical, only battle-tested software should be deployed in order to reduce risk. If you want the latest and greatest then put it on a desktop or other non-critical system.

This is the thought process behind Ubuntu's LTS (long-term support) strategy. You can update to regular releases if you want, but there are periodic stable releases. Every few versions focus on stability and are supported for longer with fewer major changes introduced over their life. The idea is to provide a stable release for mission-critical systems (e.g. servers) where "changing random things" can break stuff. These LTS releases typically only receive security and bug fixes, with new features being reserved for the standard release cycle.

Other vendors follow similar configuration management practices as well, supporting older versions with security patches. Once a newer version has proven to be stable in the wild, a company may upgrade their critical systems to it.

TL;DR: stability and the lack of nasty surpises.


答:
There can be several reasons to stay with an older release:

New releases may cost money for a new license. If the older release is sufficient, why spend the money?

New releases may cost money and/or time (a.k.a. money) to learn and/or install. Again, why bother if the older release works?

New releases may break things. This may be intentional (removing deprecated behaviors that some people weren't quite done using), or it may be a bug. Either way, the new version doesn't work, but the old does.

Title: Is there a reason for support multiple different releases?

Body:
I have a discussion with my team recently and I heard a suggestion for deploying multiple releases. Such as version (newest) and version (old).
But I am thinking what would be the reason for customer want to use the older version. What if the bug was introduced in the older version we would have to make additional support to it.

I see there are benefits of using older version. Maybe I am wrong but what would be the reason why people want the older releases?? and if the trade off wasnt worth it (support vs demand) then why are we plan to support multiple releases?


问:
Can I enforce the overriding of GetHashCode() and Equals() methods for users of a generic container class?
I have a container class similar to the one below (with much of the logic omitted):

```<code>class Container<T>
{
    Dictionary<T, TWrapped> contains = new Dictionary<T, TWrapper>();

    public void Add(T item)
    {
        TWrapped wrappedItem = new TWrapped(item);
        contains[item] = wrappedItem;

        // logic involving wrappedItem...
    }

    public bool Contains(T item)
    {
        return contains.ContainsKey(item);
    }

    // Item has been updated, so Sort called on container
    public void Sort(T item)
    {
        TWrapped wrappedItem;
        if(contains.TryGetValue(item, out wrappedItem))
        {
            // sort the wrappedItem within the container...
        }
    }

}
</code>```

Is there some way of either telling users of Container that T will be used as a dictionary key or, equivalently, of forcing users to have overridden GetHashCode() and Equals() ?

Further Info

My actual container class implements a heap implicitly with an array. To do so, items are wrapped with a class that contains index information for finding parents and children within the array. This wrapper class is private within the heap to avoid unintended tampering with the index values.

I now wish to support re-sorting of specific items in the heap; however, to map from the user supplied item to its wrapped representation in the array, I need a dictionary to store such a mapping... hence the GetHashCode() Equals() woes.

Any criticisms of the design would be welcome!

答:
When it comes to reference types (classes), you're already ok since those have Equals and GetHashCode implemented properly even without overriding.

When it comes to value types (structs, enums, ...), these should always override Equals and GetHashCode in meaningful manner as well as be immutable as per MSDN design guidelines - struct should implement IEquatable<T>; and transitively IEquatable<T> should override GetHashCode and Equals (Notes to implementors part).

If you want to really express this requirement to the consumer, consider adding a following generic constraint:

```<code>public class Container<T> where T : IEquatable<T>
</code>```

This will most probably only cause nuisance to consumers however, as they will be forced to needlessly implement IEquatable<T> on classes.

Another option is to force every consumer to supply an IEqualityComparer<T> to your Container<T> which will then be used by the Dictionary:

```<code>public class Container<T>
{
     private Dictionary<T, TWrapped> _contains;

     public Container(IEqualityComparer<T> comparer)
     {
         _contains = new Dictionary<T, TWrapped>(comparer);
     }

     // rest of implementation...
}
</code>```

Presumably, most consumers will do this

```<code>var container = new Container<T>(EqualityComparer<T>.Default);
</code>```

but it feels nice to somehow mirror the Dictionary's ctors for increased flexibility. If I wanted ordinal case-insensitive string keys, I could do

```<code>var container = new Container<string>(StringComparer.OrdinalIgnoreCase);
</code>```

Body:
When it comes to reference types (classes), you're already ok since those have Equals and GetHashCode implemented properly even without overriding.

When it comes to value types (structs, enums, ...), these should always override Equals and GetHashCode in meaningful manner as well as be immutable as per MSDN design guidelines - struct should implement IEquatable<T>; and transitively IEquatable<T> should override GetHashCode and Equals (Notes to implementors part).

If you want to really express this requirement to the consumer, consider adding a following generic constraint:

public class Container<T> where T : IEquatable<T>

This will most probably only cause nuisance to consumers however, as they will be forced to needlessly implement IEquatable<T> on classes.

Another option is to force every consumer to supply an IEqualityComparer<T> to your Container<T> which will then be used by the Dictionary:

public class Container<T>
{
     private Dictionary<T, TWrapped> _contains;

     public Container(IEqualityComparer<T> comparer)
     {
         _contains = new Dictionary<T, TWrapped>(comparer);
     }

     // rest of implementation...
}

Presumably, most consumers will do this

var container = new Container<T>(EqualityComparer<T>.Default);

but it feels nice to somehow mirror the Dictionary's ctors for increased flexibility. If I wanted ordinal case-insensitive string keys, I could do

var container = new Container<string>(StringComparer.OrdinalIgnoreCase);


答:
Although technically not completely correct, C++ is still considered a superset of C, was inspired by it and as such appropriated some of its properties, integer division being one of them.

C was mostly designed to be efficient and fast, and integers are generally much faster than floating points, because the integer type is tied to hardware, whereas floating points need to be calculated.

When the / operand recieves two integers, one of the left side and one on the right, it may not even do division at all, the result may be computed using simple addition and a loop, asking how many times does the operand on the right side fit into the operand on the left.


问:
Reusing the logic in another repository in ASP.NET MVC repository pattern
I have an ASP.NET MVC4 web application, with EntityFramework for data access. In the application I have two repositories as follow (this is only an example not my real code):

public class CustomerRepository
{
     ICustomerContext _db;

     public CustomerRepository(ICustomerContext db)
     {
          _db = db;
     }

     ...

     public void DeactivateCustomer(int customerId)
     {
         var customer = _db.Customers.Single(x => x.CustomerId == customerId);
         customer.IsActive = false;
         _db.SaveChanges();
     }
}
```

<p>And</p>

<pre class="lang-cs prettyprint-override"><code>public class ItemRepository
{
     IItemContext _db;

     public ItemRepository(IItemContext db)
     {
         _db = db;
     }

     ...

     public void DeactivateItem(int itemId)
     {
         var item = _db.Items.Single(x => x.ItemId == itemId);
         item.IsActive = false;

         // The problem is here
         new CustomerRepository().DeactivateCustomer(item.CustomerId);

         _db.SaveChanges();
     }
}
</code>```

The ItemRepository wants to use the logic of deactivating the Customer from the CustomerRepository without copying the code, or couple both repositories like the example above.

I also want to make both actions (deactivating the item, and deactivating the customer) execute in one transaction (maybe one call to SaveChanges())

Is there any design pattern that can achieve these requirements?

答:
In my experience, trying to make a framework like EF work in a repository pattern is not the best if you really want to bundle transaction and separate functionality out into Repo's like that. I would have the MVC controller instantiate an EF data context, and be responsible for calling "SaveChanges()" after its done any active-record data manipulations. For DRY's sake, you can move all those manipulation functions to a common library that takes IItemContext as a method or constructor param. That lib might look something like:

```<code>public class IItemDataManipulator
        {
            private readonly IItemContext _db;

            public IItemDataManipulator(IItemContext db)
            {
                _db = db;
            }

            public void DeactivateCustomer(int custId)
            {
                var customer = _db.Customers.Single(x => x.CustomerId == customerId);
                customer.IsActive = false;
            }

            public void DeactivateItem(int itemId)
            {
                var item = _db.Items.Single(x => x.ItemId == itemId);
                item.IsActive = false;
                DeactivateCustomer(item.customerId);
            }
        }
</code>```

And I wouldn't bother adding single-line EF queries to that library for basic object retreival. If you want to lock things down more, put this class in the same library as the EF datacontext and mark all the setters INTERNAL for stuff that you ONLY want to be able to change inside this common library.

Body:
In my experience, trying to make a framework like EF work in a repository pattern is not the best if you really want to bundle transaction and separate functionality out into Repo's like that. I would have the MVC controller instantiate an EF data context, and be responsible for calling "SaveChanges()" after its done any active-record data manipulations. For DRY's sake, you can move all those manipulation functions to a common library that takes IItemContext as a method or constructor param. That lib might look something like:

public class IItemDataManipulator
        {
            private readonly IItemContext _db;

            public IItemDataManipulator(IItemContext db)
            {
                _db = db;
            }

            public void DeactivateCustomer(int custId)
            {
                var customer = _db.Customers.Single(x => x.CustomerId == customerId);
                customer.IsActive = false;
            }

            public void DeactivateItem(int itemId)
            {
                var item = _db.Items.Single(x => x.ItemId == itemId);
                item.IsActive = false;
                DeactivateCustomer(item.customerId);
            }
        }

And I wouldn't bother adding single-line EF queries to that library for basic object retreival. If you want to lock things down more, put this class in the same library as the EF datacontext and mark all the setters INTERNAL for stuff that you ONLY want to be able to change inside this common library.


答:
Why would you use Windows 7, while Microsoft released newer versions meanwhile? Similarly, one can decide to keep an older version of Linux, or an older version of Python.

Some factors one should take in account :

The price of the new version.

The operations cost of upgrading.

The time needed to learn the new version.

Backwards compatibility: if you have built an app for Python 2, you don't necessarily want to spend the next two months adapting it for Python 3.

Dependencies: the next OS doesn't necessarily support a library you use.

New bugs: what if the new version introduces new bugs the old version doesn't have?

And most importantly, what if you just don't need the new version because the previous one responds to all your needs?


答:
One thing I would like to point out is that all your Add methods are not necessary. If you expose the List<T> like you do, you can use them for adding. And you can use the collection initializer syntax for that:

```<code>var institutions = new List<Institution>
{
    new Institution("My college")
    {
        Terms =
        {
            new Term("2016", "Spring")
            {
                Courses =
                {
                    new Course("Math 210")
                    {
                        Assignments =
                        {
                            new Assignment("Chapter 1")
                        }
                    }
                }
            }
        }
    }
};
</code>```

On first sight, this does not look any better than your original, but I believe it reflects the intention of the code better. (And it probably won't look as bad in more realistic code.)

Title: Handling Multiple Collections in C#

Body:
One thing I would like to point out is that all your Add methods are not necessary. If you expose the List<T> like you do, you can use them for adding. And you can use the collection initializer syntax for that:

var institutions = new List<Institution>
{
    new Institution("My college")
    {
        Terms =
        {
            new Term("2016", "Spring")
            {
                Courses =
                {
                    new Course("Math 210")
                    {
                        Assignments =
                        {
                            new Assignment("Chapter 1")
                        }
                    }
                }
            }
        }
    }
};

On first sight, this does not look any better than your original, but I believe it reflects the intention of the code better. (And it probably won't look as bad in more realistic code.)