问:
Generic Sorting of Lists<>
I have several Lists<> that holds objects of different classes.

```<code>List<classA> listA;
List<classB> listB;
List<classC> listC;
//...
List<classM> listM;
</code>```

The classes do not relate in any way and have nothing in common except that they might have a single property marked with an Attribute SortBy=true

```<code>    [CustomObjectComparerAttribute(IncludeInCompare = true, Title = "View Order", SortBy=true)]
    public int ViewOrder { get; set; }
</code>```

What I would like to do is to have a generic function that accepts a list of any sort. This is problem Nr 1, because I can not figure out a way to make a function accept Lists<> of different types.

```<code>private List<object> SortList(List<object> aList)  //<-- this is not allowed (problem 1)
{
    //Get which property we sort by...
    PropertyInfo  prop = GetPropertyToSortBy(objectA);

    //Sort the list
    //Problem Nr 2: How do I get `PropertyInfo prop` in the statement below
    List<Order> SortedList = aList.OrderBy(o=>o.ThePropToSortBy).ToList();
}
    private PropertyInfo GetPropertyToSortBy(object o)
    {
        Type t = o.GetType();
        foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (Attribute.IsDefined(prop, typeof(CustomObjectComparerAttribute)) && ((CustomObjectComparerAttribute)Attribute.GetCustomAttribute(prop, typeof(CustomObjectComparerAttribute))).SortBy == true)
            {
                return prop;
            }
        }
        return null;
    }
</code>```

I feel that Im attacking this problem from the wrong angle. Am I on the right track?, and if so, how can I solve my problems?

if not, can you point me in the right direction?

答:
Your specific problems are relatively easily solved.

Problem 1 is just a syntax issue for how to write methods with generic type parameters. In your case this would be:

```<code>private List<T> SortList<T>(List<T> aList)
</code>```

It's the <T> after the method name which allows you to use T as a generic type parameter in the rest of the signature

Problem 2 just requires a bit of murky digging into reflection classes. You already have a ProperyInfo instance, so you just need to use PropertyInfo.GetValue, documented here. In other words:

```<code>List<Order> SortedList = aList.OrderBy(o=>prop.GetValue(o)).ToList();
</code>```

You'll also run into some secondary problems- for example, reflection is quite slow, and you're going to be using it many times while sorting. Performance often isn't a primary concern, but for something like sorting a list it's potentially important. I don't know off the top of my head if it'd actually be an issue in this case... but finding out would require worrying about it, research, and all that other stuff you'd rather just avoid altogether.

Also, this is all pretty complex! Now to do something as simple as a list, you're having to deal with attributes, reflection and all that muck.

The route cause of your problems is that you're trying to expose something that should be behavior as metadata. This is a slightly unusual variant of a more common issue that crops up in OO design: exposing something that should be behavior as data.

Fortunately, .NET already gives us a good way to let a class define how it should be sorted in the form of behavior: the IComparable<T> interface. Again, you're probably best off reading the documentation, but in your case, instead of writing:

```<code>public class SomeSortableThing
{
    [CustomObjectComparer]
    public int SortByMe {get; set;}
}
</code>```

You'd write:

```<code>public class SomeSortableThing : IComparable<SomeSortableThing>
{
    public int SortByMe {get; set;}
    public int CompareTo(SomeSortableThing other)
    {
        return SortByMe.CompareTo(other.SortByMe);
    }
}
</code>```

This gives us the advantages:

There's no need for reflection or attributes

It's idiomatic

It's easy to use- any consumer can just use the standard sorting methods without needing any special helper method/class

It's much more flexible. If you want to order by one property then another, you can do that easily, rather than having to invent a whole new way to represent that through attributes

Our sortable properties don't need to be public, they can be encapsulated if that's appropriate.

You can interchangeably sort on properties and fields, without needing to support that in your reflection.

Title: Generic Sorting of Lists<>

Body:
Your specific problems are relatively easily solved.

Problem 1 is just a syntax issue for how to write methods with generic type parameters. In your case this would be:

private List<T> SortList<T>(List<T> aList)

It's the <T> after the method name which allows you to use T as a generic type parameter in the rest of the signature

Problem 2 just requires a bit of murky digging into reflection classes. You already have a ProperyInfo instance, so you just need to use PropertyInfo.GetValue, documented here. In other words:

List<Order> SortedList = aList.OrderBy(o=>prop.GetValue(o)).ToList();

You'll also run into some secondary problems- for example, reflection is quite slow, and you're going to be using it many times while sorting. Performance often isn't a primary concern, but for something like sorting a list it's potentially important. I don't know off the top of my head if it'd actually be an issue in this case... but finding out would require worrying about it, research, and all that other stuff you'd rather just avoid altogether.

Also, this is all pretty complex! Now to do something as simple as a list, you're having to deal with attributes, reflection and all that muck.

The route cause of your problems is that you're trying to expose something that should be behavior as metadata. This is a slightly unusual variant of a more common issue that crops up in OO design: exposing something that should be behavior as data.

Fortunately, .NET already gives us a good way to let a class define how it should be sorted in the form of behavior: the IComparable<T> interface. Again, you're probably best off reading the documentation, but in your case, instead of writing:

public class SomeSortableThing
{
    [CustomObjectComparer]
    public int SortByMe {get; set;}
}

You'd write:

public class SomeSortableThing : IComparable<SomeSortableThing>
{
    public int SortByMe {get; set;}
    public int CompareTo(SomeSortableThing other)
    {
        return SortByMe.CompareTo(other.SortByMe);
    }
}

This gives us the advantages:

There's no need for reflection or attributes

It's idiomatic

It's easy to use- any consumer can just use the standard sorting methods without needing any special helper method/class

It's much more flexible. If you want to order by one property then another, you can do that easily, rather than having to invent a whole new way to represent that through attributes

Our sortable properties don't need to be public, they can be encapsulated if that's appropriate.

You can interchangeably sort on properties and fields, without needing to support that in your reflection.


问:
Sharing functionality between platforms and languages
I'm in a situation where I already have a working, high-performance C++ program with GTK and OpenGL that renders data as a real-time graph. The data is saved as a report in a database which can be looked up at a later date from a browser. I now need to display those same graphs from the web-based reports (this wasn't in the original requirements).

I've tried generating the graphs from PHP, but drawing the whole thing with GD takes more than 20 seconds. I'm in the process of rewriting this in Javascript using canvas, which seems to be okay, although now I have to transfer all that data to the browser and parse it, which is still problematic.

But the real problem for me is that I'm actually writing the same program twice: in C++ with OpenGL and in Javascript with canvas.

I'm looking for general advice on how to "reuse" code between different platforms that support different languages, such as between a desktop environment and a web page. Are there tools that can help? Is there any way I can avoid maintaining two different codebases that do the same thing?

My ideas so far, none of which are particularly interesting:

Reuse the code. Find a way of to actually share the code, such as using a C++ program as a CGI. This won't work if the language isn't supported by the platform (such as in a browser).

Reuse the output: Write the program once, generate the output (such as an image) and make the other programs "viewers". This won't work if the output is too large to pass around.

Translate the code: Use some automated tool to translate from one language (or a meta-language) to another. If such a tool exists, I could use recommendations.

Reuse the bytecode: Use a language that compiles to bytecode that can run on various platforms. Apart from Java applets (which most people have disabled nowadays), I don't know of anything else that runs in browsers.

Develop my own universal language: Ain't nobody got time for that.

答:
If you already have the C++ code, I would err towards #2 (making the C++ a service that the client code calls into). If the output is too large, that generally means the data will be too large to send to the client to render. This approach also would let you have the client specify what size/resolution they actually need, so the server can not send the entire thing over the wire.

As for #3, I know there already exists a C to JavaScript compiler. Vile, I know... I don't know how well it will deal with ui elements, and I don't know if there's a good C++ analog/extension (or if your code is easily portable to C) - but it's maybe worth 15 minutes of google due diligence.

ContentLicense: CC BY-SA 3.0


问:
Inheriting and storing objects that contain different types of other objects
To start off, this is more of a best-practice question than anything.

Introduction to the Environment

I have myself an abstract class. Let's call this class Item. I also have another abstract class, we'll call this one Container. The Container class inherits the Item class.

Here's my dilemma: I'm trying to right-properly design the OOP portions of it, and I'm having a bit of an issue due to my desire to abstract away as much as possible, while still creating maintainable and understandable code.

Let's start with some code:

```<code>public abstract class Item
{
    private Guid _Guid;
    private float _Weight;

    public Guid Guid { get { return _Guid; } set { _Guid = value; } }
    public float Weight { get { return _Weight; } set { _Weight = value; } }

    public virtual ItemType ItemType { get { return ItemType.None; } }
}

public abstract class Container : Item
{
    private float _MaxWeight;
    private List<Item> _Items;

    public List<Item> Items { get { return _Items; } }
    public float MaxWeight { get { return _MaxWeight; } set { _MaxWeight = value; } }
    public abstract ContainerType ContainerType { get; }

    public sealed override ItemType ItemType { get { return ItemType.Container; } }
}
</code>```

So, with this code the intention is for a Container to be able to be treated as an Item, with a few exceptions. (The container will have additional properties, etc.)

The issue, is that not all Item objects can be added to a Container. In fact, only Container objects that have a smaller Container.MaxWeight or non-Container Item objects can be added.

As of now, this restriction cannot be placed. My initial thought was to create an ItemCollection inside the Container class, that would essentially hold all of the Item objects within it. This would allow me to implement my own ItemCollection.Add method which would perform this filter.

The issue comes into play when I introduce my third class. Let's call it a Backpack. This inherits Container and looks as follows:

```<code>public class Backpack : Container
{
    public sealed override ContainerType ContainerType { get { return ContainerType.Backpack; } }
}
</code>```

Mind you - the Backpack (as we are calling it) will only be able to hold Item objects, or Container objects with a smaller Container.MaxWeight in them.

This also means that I may yet have other classes (let's use, for example, Pouch) that will also inherit Container, but which cannot contain other Container objects.

Lastly, there may also be additional classes that cannot hold Item objects, but only hold Container objects. (See, for example, Inventory.)

```<code>/// <summary>
/// Represents a collection of <see cref="Container"/> objects owned by an <see cref="Actor"/>.
/// </summary>
public class Inventory : Container
{
    public sealed override ContainerType ContainerType { get { return ContainerType.Inventory; } }
}
</code>```

Question Statements

Is this the best way to do it? Should I implement the ItemCollection as I intended? What about Container objects that can only hold other Container objects?

Should I use the ContainerType.Inventory to indicate that this object can only hold other Inventory objects? Should I use the ContainerType.MaxWeight value on it instead? (Any objects that can only hold Container objects won't really have a MaxWeight. The MaxWeight an Actor can hold is determined by their fitness.)

Should I make an additional class that inherit Container that can only hold other Container objects, then inherit Inventory from this? Likewise, should I create another class inheriting from Container that allows or disallows the addition of Item objects only?

Additional Notes/Jargon

The idea is to force the programmers (mostly me) to properly handle each Container and Item as they should be. The issue lies in the fact that there are different types of Container objects. Also, do note that this is not all of the code involved, but the additional code I excluded is irrelevant to this issue. Also note, the two additional classes I mentioned (Inventory and Backpack) are completely concrete. I will be working directly with those. I also want to have common infrastructure between them, so that any Item that is a Container can be worked in a general manner. (Rather than casting to the appropriate concrete class.)

答:
The direction where you are going is great. I would make a few tweaks to this design like so:

```<code>public abstract class Container : Item
{
    private float _MaxWeight;
    private List<Item> _Items;

    public List<Item> Items { get { return _Items; } }
    public float MaxWeight { get { return _MaxWeight; } set { _MaxWeight = value; } }
    public abstract ContainerType ContainerType { get; }

    public IEnumerable<IDepositFilter> Filters { get; set; } // Probably a factory can stuff filters as required per each type.

    public void DepositItem(Item item) {
        foreach(var filter in Filters) {
            if(!filter.IsAllowed(item)) {
                throw new ItemNotAllowedException();
            }
        }

        _Items.Add(item);
    }
}

public interface IDepositFilter
{
    bool IsAllowed(Item item);
}

public class DefaultContainerFilter : IDepositFilter {
    // probably do nothing here
}

public class OversizeContainerFilter : IDepositFilter
{
    // Check if the size of the new deposit is larger than leftover space in this container
}

public class ItemTypeFilter : IDepositFilter
{
    // check what is being deposited and allow/disallow accordingly.
}
</code>```

Notice, I introduced a filter collection that should be used when you are adding something to your container. You can add as many filters as you want to your container of a specific type. Each filter does one and only one check.

I also remove the ItemType as it seems redundant - you can use classes themselves to determine the type.

Reuse the filters on anything you want :)

Hope this helps.

Body:
The direction where you are going is great. I would make a few tweaks to this design like so:

public abstract class Container : Item
{
    private float _MaxWeight;
    private List<Item> _Items;

    public List<Item> Items { get { return _Items; } }
    public float MaxWeight { get { return _MaxWeight; } set { _MaxWeight = value; } }
    public abstract ContainerType ContainerType { get; }

    public IEnumerable<IDepositFilter> Filters { get; set; } // Probably a factory can stuff filters as required per each type.

    public void DepositItem(Item item) {
        foreach(var filter in Filters) {
            if(!filter.IsAllowed(item)) {
                throw new ItemNotAllowedException();
            }
        }

        _Items.Add(item);
    }
}

public interface IDepositFilter
{
    bool IsAllowed(Item item);
}

public class DefaultContainerFilter : IDepositFilter {
    // probably do nothing here
}

public class OversizeContainerFilter : IDepositFilter
{
    // Check if the size of the new deposit is larger than leftover space in this container
}

public class ItemTypeFilter : IDepositFilter
{
    // check what is being deposited and allow/disallow accordingly.
}

Notice, I introduced a filter collection that should be used when you are adding something to your container. You can add as many filters as you want to your container of a specific type. Each filter does one and only one check.

I also remove the ItemType as it seems redundant - you can use classes themselves to determine the type.

Reuse the filters on anything you want :)

Hope this helps.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Nothing is really evil not even weapons, yet we sometimes consider them as such. However with weapons we usually have a certain level of respect, we are very much aware of their danger and use them with caution; however there are still people too stupid to use them.

The same applies to any tool, the more difficult the consequences of abusing those tools are, the more likely people are abusing them.

In programming everything is more or less virtual, a program is a representation of our thought process and the long term consequences of not understanding something entirely or getting it slightly wrong are a lot harder to determine, then the immediate danger of death we are faced with when handling a gun.

This makes the tools we use and have at our disposal a lot harder to use but it also gives us an easy way to measure the skill of a programmer. The knowledge of when and how to use the tools you have is crucial to become a good programmer. You can always play it safe by restricting the set of tools but just to the guy to whom everything looks like a nail, eventually you will encounter something that no amount of hitting will fix.

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


答:
Sharing functionality between languages is a complex and difficult-to-solve problem, so I doubt you'll find a general solution. The desire to share code is a lot of the motivation behind everything from Node.js to Xamarin.Forms to Emscripten.

I'm not clear from your description where you want to process the data and where the data comes from. In our case, we did a variation of your #1: we modified our C++ plotting code to take an abstract PlotOutput class. For the desktop app, it used a local GUI implementation; for the web app, it ran server-side and used a PlotOutput implementation that turned the plot into Flot JSON for use by a web app.  It's worked well for us, although we didn't need anywhere near 60fps. (Switching from JSON to JavaScript typed arrays would be one obvious source of performance improvement.)

Another possible solution is to use Emscripten to compile your C++ to JavaScript. Mozilla's blog has a good overview of porting a game to Emscripten.

Title: Sharing functionality between platforms and languages

Body:
I'm in a situation where I already have a working, high-performance C++ program with GTK and OpenGL that renders data as a real-time graph. The data is saved as a report in a database which can be looked up at a later date from a browser. I now need to display those same graphs from the web-based reports (this wasn't in the original requirements).

I've tried generating the graphs from PHP, but drawing the whole thing with GD takes more than 20 seconds. I'm in the process of rewriting this in Javascript using canvas, which seems to be okay, although now I have to transfer all that data to the browser and parse it, which is still problematic.

But the real problem for me is that I'm actually writing the same program twice: in C++ with OpenGL and in Javascript with canvas.

I'm looking for general advice on how to "reuse" code between different platforms that support different languages, such as between a desktop environment and a web page. Are there tools that can help? Is there any way I can avoid maintaining two different codebases that do the same thing?

My ideas so far, none of which are particularly interesting:

Reuse the code. Find a way of to actually share the code, such as using a C++ program as a CGI. This won't work if the language isn't supported by the platform (such as in a browser).

Reuse the output: Write the program once, generate the output (such as an image) and make the other programs "viewers". This won't work if the output is too large to pass around.

Translate the code: Use some automated tool to translate from one language (or a meta-language) to another. If such a tool exists, I could use recommendations.

Reuse the bytecode: Use a language that compiles to bytecode that can run on various platforms. Apart from Java applets (which most people have disabled nowadays), I don't know of anything else that runs in browsers.

Develop my own universal language: Ain't nobody got time for that.


问:
Storing session key in a hidden field
Background:

I have a question which is outline at Use different local storage between windows. The very high level question is "How can I keep tabs and windows sessions from clashing".

Requirement:

I want to be able to have separate "sessions" for each tab(s) or window(s).

Problem:

The problem is if I store the data in cookies or in HTML Local Storage, it will be very difficult prevent the user from screwing up the data by opening s new window or tab and keeping the data separate.

Possible Solution:

Since Tabs and Windows share cookies and HTML Local Storage under the same instance. My question to here is, how safe is it to store a unique key in a hidden field to use to retrieve the cookies or HTML Local Storage? By doing it this way, if a new page is created (or Tab), this field is not shared across tabs and windows. What's the security risk in this approach and its a good idea?

For example, I would store the session id or Key in a hidden field:

```<code>  <input type="hidden" name="sessionId" id="sessionId" value="" />
</code>```

答:
Cookies are primarily attractive because of the ability to store long-lived values and the convenience of not having to explicitly submit session identification with each request (because the browser will). You can also pretty effortlessly hide cookie values from scripts, whereas the same protection over a form field or variable requires a more verbose solution.

But, since you'll probably be rolling your own session management library, you'll need to be aware of a few things -- probably more than I have listed here -- but as a start, you need to protect against:

Predictable session ID's which may allow users to "find" and hijack another

Allowing users to provide their own Session ID; only ID's generated by the server should be recognized

Allowing scripts to see the session ID

The first two concerns apply to any type of session. They're notable largely because you'll likely be rolling some custom session management code. The third concern applies much more-so, but not exclusively, to cookieless sessions, because cookie headers can be flagged as http-only cookies.

To prevent scripts from seeing a value, you need to close over the ID with some care:

```<code>var SessionScope = (function() {
  var o = {};

  // outside scripts can't see this:
  var session_id = '1234';

  // these methods can see session_id and use it to channel/sign requests
  o.get = function(url, data) { };
  o.post = function(url, data) { };
  o.whateverelse = function() { };

  return o;
})();
</code>```

To be clear, you ideally need to ensure that the SessionScope (or whatever) is built in such a way that it doesn't even have ties to a constructor that could be toString()'d.

Now, I understand the risk of letting scripts see your session ID's to be pretty low in most cases. It becomes most problematic when you display data submitted by one user to another user, or when you incorporate less-than-trustworthy 3rd party libraries. That said, if you go this route, it's perfectly feasible to add the extra protection, so you should.

And again, you'll want to consider that, if you depart from storing session ID's in cookies, you'll likely either lose or impede the ability to reattach to the session without asking the user to "find" it in some way.

With all of that said, you may not actually want distinct "sessions" at all. The best solution may still just be a single session. If your user is logged in using the same credentials and permissions on each tab, and you need to track data related to a particular window, tab, or view on both the client and server, you probably just want a collection in the session. But in that type of solution, view/tab identifiers aren't usually necessary because the view only asks for things relevant to itself.

Cross-talk between tabs and views is avoided by a combination of keeping things out of the "global" session that don't belong there and only asking for things you need.

But, if that's not feasible for some reason, you could consider adding a collection of view collection to your session model and passing a viewid around. In this case, you wouldn't have to worry about all the security concerns of session key management and protection (assuming you're properly using a strong session system). The view keys would only be relevant to the session, so a leaked viewid isn't relevant to anyone else, and therefore not a significant threat.

Title: Storing session key in a hidden field

Body:
Cookies are primarily attractive because of the ability to store long-lived values and the convenience of not having to explicitly submit session identification with each request (because the browser will). You can also pretty effortlessly hide cookie values from scripts, whereas the same protection over a form field or variable requires a more verbose solution.

But, since you'll probably be rolling your own session management library, you'll need to be aware of a few things -- probably more than I have listed here -- but as a start, you need to protect against:

Predictable session ID's which may allow users to "find" and hijack another

Allowing users to provide their own Session ID; only ID's generated by the server should be recognized

Allowing scripts to see the session ID

The first two concerns apply to any type of session. They're notable largely because you'll likely be rolling some custom session management code. The third concern applies much more-so, but not exclusively, to cookieless sessions, because cookie headers can be flagged as http-only cookies.

To prevent scripts from seeing a value, you need to close over the ID with some care:

var SessionScope = (function() {
  var o = {};

  // outside scripts can't see this:
  var session_id = '1234';

  // these methods can see session_id and use it to channel/sign requests
  o.get = function(url, data) { };
  o.post = function(url, data) { };
  o.whateverelse = function() { };

  return o;
})();

To be clear, you ideally need to ensure that the SessionScope (or whatever) is built in such a way that it doesn't even have ties to a constructor that could be toString()'d.

Now, I understand the risk of letting scripts see your session ID's to be pretty low in most cases. It becomes most problematic when you display data submitted by one user to another user, or when you incorporate less-than-trustworthy 3rd party libraries. That said, if you go this route, it's perfectly feasible to add the extra protection, so you should.

And again, you'll want to consider that, if you depart from storing session ID's in cookies, you'll likely either lose or impede the ability to reattach to the session without asking the user to "find" it in some way.

With all of that said, you may not actually want distinct "sessions" at all. The best solution may still just be a single session. If your user is logged in using the same credentials and permissions on each tab, and you need to track data related to a particular window, tab, or view on both the client and server, you probably just want a collection in the session. But in that type of solution, view/tab identifiers aren't usually necessary because the view only asks for things relevant to itself.

Cross-talk between tabs and views is avoided by a combination of keeping things out of the "global" session that don't belong there and only asking for things you need.

But, if that's not feasible for some reason, you could consider adding a collection of view collection to your session model and passing a viewid around. In this case, you wouldn't have to worry about all the security concerns of session key management and protection (assuming you're properly using a strong session system). The view keys would only be relevant to the session, so a leaked viewid isn't relevant to anyone else, and therefore not a significant threat.


问:
Automatic code correction, Good or Bad?
We have a large team comprising of developers, interns who write rails and backbone js code with large codebase.

We already have tools like JSCS and code climate to analyze the code and report errors to the developers so that they fix it.

I tried to introduce fixmyjs, tool which corrects silly syntax errors automatically. One other senior developer suggested to hold on to this since we are still in transition of team of developers who write code, to team of developers who understands what writing good code means.

I understand the concern that, if this is introduced, developers might find it easy to get their code approved without understanding how to write good code, since the tool will be doing that for them.

My argument is that ultimate aim of any organization/team is to deliver products as soon as possible without compromising on quality. And this tool helps us to do that.

Educating someone is not the primary concern when you are doing business. There should be equal responsibility on the developer to educate himself to understand what needs to be done.

I feel not using a tool, because that will make developers not learn what needs to be done is not correct.

Your thoughts please.

答:
I would argue: Probably good for your business's productivity; but potentially bad for your developers' careers.

It's probably good for your business's productivity because, in some respect, all code is "rewritten" before it's executed. Adding another layer of rewrites can be considered a language mutation or extension. And if the extensions help productivity, that's good. In fact, congrats, you've created a new dialect. (hooray...)

But, it's only probably good for your business's productivity because certain "language extensions" can promote sloppiness or even just "a different mode of thinking" that extends into areas of that code that aren't being rewritten, or possibly can't be rewritten.

It's potentially bad for your developers' careers because they could become accustomed to writing a sub-language that only your organization uses. If your developers aren't encouraged to just "write it right" according to predominating standards, you are potentially harming their future careers -- oh so slightly.

That said, I would encourage the incorporation of extensions that your developers are fully aware of, and which rewrite code only for the purpose of increasing productivity by expanding on condensed code. Extensions shouldn't "correct" broken code, allowing developers to be blissfully ignorant that their code is wrong; extensions should warn about or fail broken code.

To be clear: your extensions should be called extensions, and they should only be in the business of taking well-documented "short things" and expanding them out "somewhat longer things."

Title: Automatic code correction, Good or Bad?


答:
Unfortunately, exposing public List Items {get;} breaks the whole encapsulation and protection mechanisms. The using code can just do container.Items.Add and put whatever they want. (which is a problem in the other answer as well).

More and more I start to prefer composition instead of inheritance, and when some form of inheritance is needed (to avoid duplicated code), a decorator pattern may come in place.

And for the sake of the argument (I understand that the code sample is not complete), I do not see a reason of using an abstract class to start with. Interface may be more appropriate, if we want just to describe what properties an item can have.

Although the above is the way to go, if there is a "real" need to use inheritance, here is an example code how I would approach this:

```<code>public abstract class Item
{
   public string SomeData{get;set;)
}

public abstract class Container : Item
{
    private readonly List<Item> _items;
    public IEnumerable<Item> Items { get { return _items;}}
    public Container()
    {
       _items = new List<Item>();
    }

    public void AddItem(Item item)
    {
       if (IsValidItem(item))
       {
           _items.Add(item);
       }
    }

    protected virtual bool IsValidItem(Item item)
    {
       ///some validation logic, etc
    }
}
</code>```

With the above very simplistic/schematic design its easy to achieve the questions from the original post. In the other types of containers, it is about overriding the protected IsValid method to do whatever it need to be (incl if it has to call the base method, etc.).

Also, we do not break the encapsulation, so external consumers of the class can not add items w/o validation.

When questions start to come about reseting the container, removing items, etc., probably it's better to make your container class to inherit from Item, and implement ICollection interface, using a backing storage of internal list, and forward (trough some validation) the corresponding calls to it:

```<code>public class Container : Item, ICollection<Item>
</code>```

NOTE: As I said earlier, I will not go with this approach, it is a nightmare to test and extend. And it probably in the real world implementation is going to break one or more of the SOLID principles.

Title: Inheriting and storing objects that contain different types of other objects

Body:
To start off, this is more of a best-practice question than anything.

Introduction to the Environment

I have myself an abstract class. Let's call this class Item. I also have another abstract class, we'll call this one Container. The Container class inherits the Item class.

Here's my dilemma: I'm trying to right-properly design the OOP portions of it, and I'm having a bit of an issue due to my desire to abstract away as much as possible, while still creating maintainable and understandable code.

Let's start with some code:

```<code>public abstract class Item
{
    private Guid _Guid;
    private float _Weight;

    public Guid Guid { get { return _Guid; } set { _Guid = value; } }
    public float Weight { get { return _Weight; } set { _Weight = value; } }

    public virtual ItemType ItemType { get { return ItemType.None; } }
}

public abstract class Container : Item
{
    private float _MaxWeight;
    private List<Item> _Items;

    public List<Item> Items { get { return _Items; } }
    public float MaxWeight { get { return _MaxWeight; } set { _MaxWeight = value; } }
    public abstract ContainerType ContainerType { get; }

    public sealed override ItemType ItemType { get { return ItemType.Container; } }
}
</code>```

So, with this code the intention is for a Container to be able to be treated as an Item, with a few exceptions. (The container will have additional properties, etc.)

The issue, is that not all Item objects can be added to a Container. In fact, only Container objects that have a smaller Container.MaxWeight or non-Container Item objects can be added.

As of now, this restriction cannot be placed. My initial thought was to create an ItemCollection inside the Container class, that would essentially hold all of the Item objects within it. This would allow me to implement my own ItemCollection.Add method which would perform this filter.

The issue comes into play when I introduce my third class. Let's call it a Backpack. This inherits Container and looks as follows:

```<code>public class Backpack : Container
{
    public sealed override ContainerType ContainerType { get { return ContainerType.Backpack; } }
}
</code>```

Mind you - the Backpack (as we are calling it) will only be able to hold Item objects, or Container objects with a smaller Container.MaxWeight in them.

This also means that I may yet have other classes (let's use, for example, Pouch) that will also inherit Container, but which cannot contain other Container objects.

Lastly, there may also be additional classes that cannot hold Item objects, but only hold Container objects. (See, for example, Inventory.)

```<code>/// <summary>
/// Represents a collection of <see cref="Container"/> objects owned by an <see cref="Actor"/>.
/// </summary>
public class Inventory : Container
{
    public sealed override ContainerType ContainerType { get { return ContainerType.Inventory; } }
}
</code>```

Question Statements

Is this the best way to do it? Should I implement the ItemCollection as I intended? What about Container objects that can only hold other Container objects?

Should I use the ContainerType.Inventory to indicate that this object can only hold other Inventory objects? Should I use the ContainerType.MaxWeight value on it instead? (Any objects that can only hold Container objects won't really have a MaxWeight. The MaxWeight an Actor can hold is determined by their fitness.)

Should I make an additional class that inherit Container that can only hold other Container objects, then inherit Inventory from this? Likewise, should I create another class inheriting from Container that allows or disallows the addition of Item objects only?

Additional Notes/Jargon

The idea is to force the programmers (mostly me) to properly handle each Container and Item as they should be. The issue lies in the fact that there are different types of Container objects. Also, do note that this is not all of the code involved, but the additional code I excluded is irrelevant to this issue. Also note, the two additional classes I mentioned (Inventory and Backpack) are completely concrete. I will be working directly with those. I also want to have common infrastructure between them, so that any Item that is a Container can be worked in a general manner. (Rather than casting to the appropriate concrete class.)

Body:
Unfortunately, exposing public List Items {get;} breaks the whole encapsulation and protection mechanisms. The using code can just do container.Items.Add and put whatever they want. (which is a problem in the other answer as well).

More and more I start to prefer composition instead of inheritance, and when some form of inheritance is needed (to avoid duplicated code), a decorator pattern may come in place.

And for the sake of the argument (I understand that the code sample is not complete), I do not see a reason of using an abstract class to start with. Interface may be more appropriate, if we want just to describe what properties an item can have.

Although the above is the way to go, if there is a "real" need to use inheritance, here is an example code how I would approach this:

public abstract class Item
{
   public string SomeData{get;set;)
}

public abstract class Container : Item
{
    private readonly List<Item> _items;
    public IEnumerable<Item> Items { get { return _items;}}
    public Container()
    {
       _items = new List<Item>();
    }

    public void AddItem(Item item)
    {
       if (IsValidItem(item))
       {
           _items.Add(item);
       }
    }

    protected virtual bool IsValidItem(Item item)
    {
       ///some validation logic, etc
    }
}

With the above very simplistic/schematic design its easy to achieve the questions from the original post. In the other types of containers, it is about overriding the protected IsValid method to do whatever it need to be (incl if it has to call the base method, etc.).

Also, we do not break the encapsulation, so external consumers of the class can not add items w/o validation.

When questions start to come about reseting the container, removing items, etc., probably it's better to make your container class to inherit from Item, and implement ICollection interface, using a backing storage of internal list, and forward (trough some validation) the corresponding calls to it:

public class Container : Item, ICollection<Item>

NOTE: As I said earlier, I will not go with this approach, it is a nightmare to test and extend. And it probably in the real world implementation is going to break one or more of the SOLID principles.


问:
Deserializing an object at beginning of program which is used (much) later
I am writing a program, where in the beginning of the execution, I am instantiating a number of classifier objects using parameters stored in some files.

I later use those classifiers in multiple objects.

My question is: how should an object which uses a classifier obtain this classifier object?

The objects which use the classifiers do not even exist at the initialization time of the program and they are "far away" from the initialization class, so even if they existed, passing the classifiers through multiple classes is a code smell.

答: Make a "classifier holder" object, hand it the classifiers when they are created, and when the classifier-using objects need them, have them ask the holder to give them one.  </p>


问:
Minimizing compression overhead in a simple compression algorithm
Note: this question has been re-written to simplify and generalize the problem. The original is available below.

Suppose I created a simple compression scheme for lists of 2-digit numbers. It has 2 modes:

Mode 0: The numbers are written as-is, uncompressed.

Mode 1: Only the ones digit is written for each number, but the run of numbers must have the same tens digit. This provides 2:1 compression given an infinite list of numbers with the same tens digit.

The compressed output string must have only digits 0-9, except for the following 3-character magic values which must be used to switch the mode of compression:

*** - switch to mode 0

*x* - switch to mode 1, where x is the common tens digit for the numbers that follow. If the tens digit changes, the mode 1 switch needs to be written again, with a different common tens digit.

The compressor can switch freely between the two compression modes. So, some two ways that the list of numbers 11 12 13 14 21 22 23 24 can be encoded are:

```<code>***1112131421222324 (only mode 0, each number written out as-is)
*1*1234*2*1234      (only mode 1, only ones digits are written after the mode switches,
                     but mode 1 needed to be started twice, for each diff. tens digit)
</code>```

In the above example, using mode 1 saved 5 characters, but that is not always the case. Encoding the list 15 26 37 48:

```<code>***15263748
*1*5*2*6*3*7*4*8
</code>```

is shorter in mode 0. And obviously, in more complex texts, the modes need to be mixed correctly to provide the shortest result. For example, encoding the list 11 12 21 22 23 24 25 26 18 39:

```<code>***11122122232425261839 (only mode 0)
*1*12*2*123456*1*8*3*9  (only mode 1)
*1*12*2*123456***1839   (mode 1 then mode 0)
</code>```

the third encoding provides the shortest result, by properly mixing the encoding modes.

Given this specification, an encoder that exhaustively tries mixing the 2 modes while encoding a list of numbers will give the shortest possible compressed result. Obviously, such an encoder takes a ridiculously long time - O(n^n). Trying to think of a more efficient encoder, I got stumped.

So my question - is it possible, given the above specification, to write an encoder that would perform better than O(n^n) - that could make decisions in mixing the 2 compression modes without exhaustively trying every single combination? Or is the exhaustive algorithm the only way to get the shortest possible compressed string?

Thanks in advance to anyone who shares any insight on this. Note that my goal is to figure out the general compression problem illustrated in my question, rather than to simply find/create an efficient number list compressor.

```<code>=============================================================================
</code>```

Below is my question as it was phrased originally, in terms of text encoding

```<code>=============================================================================
</code>```

I thought up a simple UTF-16 text compression scheme that has 2 modes:

Mode 0: UTF-16 byte pairs are written as-is, uncompressed.

Mode 1: Only the least-significant-byte is written for each character, but the run of characters must have the same most-significant-byte (be from the same unicode block). This provides 2:1 compression given an infinite string of characters from the same unicode block.

Assume that it takes 3 bytes to change the mode. Switching the active most-significant-byte (unicode block) on mode 1 likewise takes 3 bytes.

Below are some examples of how UTF-16 text can be encoded given this specification. In the examples,

```<code>"a" = any character from unicode block 1
"b" = any character from unicode block 2
"===" = 3-byte value indicating mode 0 is now active
"---" = 3-byte value indicating mode 1 is now active
</code>```

So the text "aaaabbbb" (4 different characters from unicode block1, and 4 diff. chars. from unicode block 2) can be encoded as

```<code>===aaaaaaaabbbbbbbb  (each letter takes up 2 bytes)  -or-
---aaaa---bbbb       (each letter takes up 1 byte, but mode 1 needed to be started twice, because b is from a different block than a)
</code>```

In the above example, using mode 1 saved 5 bytes, but that is not always the case. Encoding the text "abab",

```<code>===aabbaabb
---a---b---a---b
</code>```

is shorter in mode 0. And obviously, in more complex texts, the modes need to be mixed correctly to provide the shortest result. For example, encoding the text "abbbbbbab",

```<code>===aabbbbbbbbbbbbaabb
---a---bbbbbb---a---b
---a---bbbbbb===aabb
</code>```

the third encoding provides the shortest result, by properly mixing the encoding modes.

I wrote an encoder, given this specification, that exhaustively tries mixing the 2 modes while encoding a string and outputs the shortest result. Obviously, this takes a ridiculously long time - O(n^n). Trying to write a more efficient encoder, I got stumped.

So my question - is it possible, given the above specification, to write an encoder that would perform better than O(n^n) - that could make decisions in mixing the 2 compression modes without exhaustively trying every single combination? Or is the exhaustive algorithm the only way to get the shortest possible compressed string?

Thanks in advance to anyone who shares any insight on this. Note that my goal is to figure out the general compression problem illustrated in my question, rather than to simply find/create an efficient text encoder.

答:
Consider:

Mode 1 is only more efficient when you have a run of the same tens digit.

Mode 1 saves 1 character for each same tens digit, except the first

It costs 2 characters to switch to mode 1.

Therefore Mode 1 only becomes advantageous after 4 similar 10s characters (costs 2, saves 3)

For example, consider if you are running in mode 0. A switch to mode 1 breaks even after 3 tens characters:

```<code>818283
*8*123
</code>```

and becomes advantageous after 4 tens characters

```<code>81828384
*8*1234
</code>```

However,

It costs 3 characters to switch back to mode 0

Therefore, it is only worthwhile switching to mode 1, if:

You have 7 or more similar tens characters (cost 2 + 3, save 6), eg

```<code>102010208182838485868710201020
10201020*8*1234567***10201020
</code>```

Or you have adjacent runs of tens characters that save you more than it costs to switch back to mode 0 (3). Again, runs of 3 gain you nothing, runs of 4 gain you 1 etc. In the example below there are 4 runs of 4 adjacent 10s, so we save 4 characters. One more than the three we need to switch back.

```<code>102010206162636471727374818283849192939410201020
10201020*6*1234*7*1234*8*1234*9*1234***10201020
</code>```

Now the above rules assume some infinite stream. In reality you can gain at the start of the stream by choosing whichever encoding you want for the first sequence, and at the end of the stream you won't have to change back to mode 0 if you have duplicate 10s right to the end. This is why your examples seem so arbitrary. They're so short that the start and end optimisations override the main rules.

Body:
Consider:

Mode 1 is only more efficient when you have a run of the same tens digit.

Mode 1 saves 1 character for each same tens digit, except the first

It costs 2 characters to switch to mode 1.

Therefore Mode 1 only becomes advantageous after 4 similar 10s characters (costs 2, saves 3)

For example, consider if you are running in mode 0. A switch to mode 1 breaks even after 3 tens characters:

818283
*8*123

and becomes advantageous after 4 tens characters

81828384
*8*1234

However,

It costs 3 characters to switch back to mode 0

Therefore, it is only worthwhile switching to mode 1, if:

You have 7 or more similar tens characters (cost 2 + 3, save 6), eg

102010208182838485868710201020
10201020*8*1234567***10201020

Or you have adjacent runs of tens characters that save you more than it costs to switch back to mode 0 (3). Again, runs of 3 gain you nothing, runs of 4 gain you 1 etc. In the example below there are 4 runs of 4 adjacent 10s, so we save 4 characters. One more than the three we need to switch back.

102010206162636471727374818283849192939410201020
10201020*6*1234*7*1234*8*1234*9*1234***10201020

Now the above rules assume some infinite stream. In reality you can gain at the start of the stream by choosing whichever encoding you want for the first sequence, and at the end of the stream you won't have to change back to mode 0 if you have duplicate 10s right to the end. This is why your examples seem so arbitrary. They're so short that the start and end optimisations override the main rules.


问:
Algorithm and data structure to match groups of users (1-5 each) into 2 balanced sets of 5 users
I'm building a matchmaking queueing service for a 5v5 team-based game.

I have a large set of users that are grouped into unique lobbies comprised of 1-5 users each. Each user has an integer based rank from 1-16. These ranks will eventually be converted to a trueskill rating, but for now, we're sticking with integers since we're importing the rankings from an existing system that is already quite accurate.

So we have lobbies of up to 5 people, and we want to create balanced matches between 10 people (5v5), combining these various lobbies in a way that is balanced and equivalent to 2 sets of 5 people. Lobbies can't be split up and the rank differential between users in a lobby can't exceed 4.

I can design the data structure in any way. Currently, I have a hash object of lobbies and a hash object of users that refer to each other.

I'm not looking for code, or even necessarily pseudocode. I'm just looking for a place to start. I'm a little lost on how I can efficiently and properly combine lobbies of various sizes into 5v5 matches, while ensuring that those two teams are sufficiently balanced in ranks (+-1.5 ranks).

答:
Calculate the total rank of all players in a single lobby.

Match with other lobby based on that. (+- 1.5 range pretty much)

Isn't it as simple as this?


问:
git workflow: read access + pull request or write access?
Suppose there is a small team with 1 senior developer and 3 junior developers working on the same repo in a team on a github organization. The senior developer has admin access. What is the most common approach in the industry to setup the access for the junior developers?

Is it giving them read access only and ask them to submit a pull request every time they change something and it will be reviewed by the senior developer?

Or is it giving them full write access?

The goal here is to maximize productivity.

答:
In my organization, all developers, both junior and senior, submit pull requests that are reviewed by other developers.  Just because you are senior doesn't mean you can't make a mistake.

But we also don't limit write access to anyone.  We trust our people to not force push to master. (And worst case, the git server is backed up.)  Just because you are junior does not mean you are not responsible.

Rules are best enforced with culture, not technology.  The last thing you want in an emergency situation is someone trying to find the person with admin privileges.  If you don't trust them with your repo, you should not have hired them.


问:
What's the simplest way to deal with events in C in this situation?
I'm writing a text-based game, in C.  I want the game to handle NPCs movement and actions in the background, while the user is making his moves.  I'd also use time-based events to tell the user when midnight is (in game-time), or to activate certain things at certain times.

I know that Dwarf Fortress is all single thread stuff, but I can't understand how that's done.  I don't know how he handles events.  Surely he's not polling.

I've never done any thread programming, or anything with sockets.  I've been programming for a while, but I know nothing about those things.

I googled options, but there seems to be a lot of stuff that comes under the heading of event-handling.  I have no idea where to start.  The first idea that comes to mind, is have two separate programs communicating through a text file, but that seems like a very ugly solution.

What's the simplest solution to handle events such as I described?

I'm currently working in Windows but I would switch over to linux if it's easier. I just happened to be using a Windows machine when I started, so it doesn't matter which.

答:
The simplest solution is to use interrupts and timers.

The interrupts indicate:

User I/O inputs

Timer expiration

Two separate programs could communicate via two pipes or msgsnd() or semaphores or mutexes or signals.

(I think there is no need for multiple programs.)

If you write the program so that everything is interrupt driven, along with a 'background' activity that is running when no interrupt is being serviced. Then the program should be 'relatively' easy to implement.

Some experience with real-time embedded program would greatly assist you in the design, coding, debugging and documenting of the program.


问:
Eclipse plugins - safe to install?
I've seen a few useful plugins for Eclipse such as jshint-eclipse. However, I'm a bit leery of installing third-party code.

Is it generally safe to install Eclipse plugins without worrying about my local system being compromised?

答:
An Eclipse plug-in is basically a Java program, running inside Eclipse (and thus with the same credentials/permissions).  Running an untrusted Eclipse plug-in is approximately as safe as running an untrusted Java program.

That said, malware authors tend not to target Eclipse.

Note that I'm assuming you aren't using some sort of weird executable plug-in installer.

Title: Eclipse plugins - safe to install?


答:
It is operating system specific (or hardware specific if you are coding some kernel-like software on the bare metal like an OS kernel -see osdev.org-, in freestanding C). Stricto sensu you probably cannot write a game in purely standard hosted C99 (without using any external library, except the C standard library using only the few functions standardized in C99): you need to use some operating system service.

I'm focusing on Linux in my answer below.

If you are coding on Linux (in hosted C, as all user programs are), you'll code your event loop around a multiplexing syscall like poll(2) (or perhaps the older select(2), which I usually don't recommend; see also epoll(7)). Read about the C10K problem. You might use some event loop library like libev or libevent.

If you are unfamiliar with most Linux syscalls (listed in syscalls(2)...), read Advanced Linux Programming.

Reading and polling the terminal is tricky on Linux (because tty-s are quite complex). You probably want to use some library, like ncurses, to make a terminal application.

If you want to code a GUI application, you'll practically use some toolkit framework like Qt or Gtk (or libsdl). They provide an event loop, and you'll need to register callbacks (read also about continuations, it is a relevant concept).

If you want to have two programs (written by you) communicating, you'll need to use some IPC machinery, notably pipe(7)-s. You'll probably need some event loop in some (or both) of them.

For time-related issues, poll(2) (so all event loop libraries built above it) is given a delay. See also time(7).

I don't recommend using signal(7)-s in your case (signals are an interrupt like abstraction provided by the OS, notably POSIX ones). If you do, be very careful, it is tricky. A signal handler is only allowed to call very few async-signal-safe functions, and the usual way is often to simply set some volatile sig_atomic_t  flag in it, to be tested and reset inside your event loop. See also POSIX signal concepts chapter.

If you are coding on a non-POSIX operating system like Windows, you need to learn how to write event loops on it, and what is the low-level system API. You'll probably find some library for that. There exist a few libraries (e.g. Qt  & POCO - both for and in C++) which are cross-platform. Windows programming is very different from POSIX programming, I know nothing about it.

Title: What's the simplest way to deal with events in C in this situation?

Body:
I'm writing a text-based game, in C.  I want the game to handle NPCs movement and actions in the background, while the user is making his moves.  I'd also use time-based events to tell the user when midnight is (in game-time), or to activate certain things at certain times.

I know that Dwarf Fortress is all single thread stuff, but I can't understand how that's done.  I don't know how he handles events.  Surely he's not polling.

I've never done any thread programming, or anything with sockets.  I've been programming for a while, but I know nothing about those things.

I googled options, but there seems to be a lot of stuff that comes under the heading of event-handling.  I have no idea where to start.  The first idea that comes to mind, is have two separate programs communicating through a text file, but that seems like a very ugly solution.

What's the simplest solution to handle events such as I described?

I'm currently working in Windows but I would switch over to linux if it's easier. I just happened to be using a Windows machine when I started, so it doesn't matter which.


答:
It depends on how you want access to your objects (Use as less abstraction as needed):

1) use a Container like a Collection or a Map for simly putting the objects in. Collections are made just for "holding" things.

2) If you need more fine grained access: build another object containing the Container.

I later use those classifiers in multiple objects.

What does later mean in this context? Get the objects when you actually need them: at the latest possible time.

they are "far away" from the initialization class, so even if they existed, passing the classifiers through multiple classes is a code smell.

Why do you think that? From what you are writing, which is very abstract, there is no way of deciding, whether it is or it is not a code smell.

If the needed objects are needed for the life-time of the object, the latest possible time would be the earliest point in the lifetime of the object who needs the other object. Constructor injection would be one way to deal with that.

Title: Deserializing an object at beginning of program which is used (much) later

Body:
I am writing a program, where in the beginning of the execution, I am instantiating a number of classifier objects using parameters stored in some files.

I later use those classifiers in multiple objects.

My question is: how should an object which uses a classifier obtain this classifier object?

The objects which use the classifiers do not even exist at the initialization time of the program and they are "far away" from the initialization class, so even if they existed, passing the classifiers through multiple classes is a code smell.


问:
How do C/C++ programs get ported to different platforms?
Java applications can run on different platforms because they always run on top of a Virtual Machine specifically developed for each platform. So, there's no native installation, you just drop the compiled jar anywhere and run it.

Now, I'm not very familiarized with the details of C/C++ development. So I'm curious, how do C/C++ programs get ported to run natively on different platforms? What would be the general steps to:

1- Write a program with a GUI that simply displays the words "Hello World" on a window.

2- Package it so that on Windows OS, it gets installed by running an installer (.exe file).

3- Package it so that on Linux, it gets installed with the apt-get command on a console.

4- Package it so that on Mac OSX, it gets installed by dropping it on the "Applications" folder.

What library would I use to display the "Hello World" window? How would this library have been written to make it work on several platforms? Are there different versions of this library for different platforms? If so, does that mean that every time I were to package the program for a specific platform, I would have to compile it using the specific version of the library for the specific platform?

I'm just trying to get a general understanding of how this process works. It would be nice to hear some go-to tools that C/C++ developers generally use for the packaging process.

答:
You have two separate issues:

How to code a C or C++ program which can easily be ported to several operating systems. The easiest way is to use some cross-platform framework library like Qt or POCO (or perhaps libsdl or GTK) which has been ported to several platforms and provides a common set of abstractions. You could also restrict yourself to purely C99 or C++11 standard conforming code -without any external non-standardized library (but then, there are many applications that you won't be able to write, see e.g. this). Notice that the POSIX specification exists (but has nothing for GUI applications!), if you follow it, your code should be able to be compiled and run on all POSIX compliant (a.k.a. Unix standard) operating systems (e.g. Linux & MacOSX & AIX, etc..., but not Windows). Otherwise, you would use conditional compilation (#if preprocessor directive) and hopefully wrap all operating-system specific services in a few translation units (to be used by the rest of your code).

How to package & deploy a program (produced by compiling your C or C++ source code) on different operating systems. This is very OS specific, and even on Linux various distributions have different package managers: you'll have to do different things for Debian and for Redhat (and perhaps even different things for various versions of Linux distributions), since Debian has *.deb packages installed with apt-get or dpkg but Redhat has *.rpm packages installed with yum or rpm! However on Linux the FHS (filesystem hierarchy standard) is helpful since it defines where files of your software should go (but how they are installed is still distribution or package manager specific).

It might be actually simpler & wiser to develop and distribute your program as a free software in source form (e.g. on github), and to expect (advanced) users and sysadmins to install it by compiling its source code (then running some installation script which would copy the binary at specific places, e.g. under /usr/local/bin/ and the configuration files at other specific places, e.g. under /etc/, etc...). Eventually your free software might become packaged in most Linux distributions, and some external contributors would provide patches to enhance your code (or port it to some other operating system).

The dependency hell may always become an issue (because you might need some specific versions of specific external libraries) - and it does not depend much on the language, you could have it in Java too! -, but package managers are more or less dealing with it.

Portability (which is relative to some specification) is mostly a mindset or an ideal: A well known quote (I forgot the attributions) is "there is no portable program, there are only some programs which have been ported to some target systems" (and that is true for many programming languages, including Java).

BTW, some programs get compiled to a plain executable binary (only), other are requiring configuration files, external resources (e.g. fonts, graphic images, web or text templates, data files, script files) or dependencies. So the complexity of their deployment may vary a lot. For example, installing and deploying GNU emacs (or firefox browser) is very different -and much more complex- than installing a command line "hello world" program (which is nearly always a single executable). A graphical Qt-based "hello world" program is probably simple to install, if you assume that the target system already has the right version of Qt appropriately installed (in a usual place & configuration).

NB: notice that the C or C++ standards does not require that the implementation runs on a computer (in principle, you could unethically use a bunch of human slaves for a standard conforming C99 or C++11 implementation), and does not require a compiler. But most implementations are compiled (some few C interpreters exist however).


答:
I take it you have something like this?

```<code>public class Main(string[] args)
{
    string param = args[0]; //load parameter from config
    Classifier c = new Classifier(param)

    SomeClass x = new SomeClass(c);
    var o = x.DoSomething();
}

public class SomeClass
{
    OtherClass o;

    //doesnt use the classifier but needs it for OtherClass,
    //hence required for passing down the chain
    public SomeClass(Classifier c)
    {
        o = new OtherClass(c);
    }

    public object DoSomething()
    {
        return o.DoSomthing();
    }
}

public class OtherClass
{
    public OtherClass(Classifier c) {} //uses classifier object 'far away'

    public object DoSomething() {}
}
</code>```

And you want to avoid either having the Classifier object passed through ever constructor in the chain, or having objects which arent the actual application reading from the config directly?

My Suggestion in these cases it that you can do one of two things

A: Check that your 'higher in the chain classes' are obeying the single responsibility principle. Would it be better just to call OtherObject directly?

B: Can you move the injected parameter to be a parameter of the function call? in this case x.DoSomething(c);

In most cases I think it is a code smell. If you code is too 'deep' in this way its likely that your objects don't just do one thing anymore but orchestrate various other classes to do multiple things. Although one layer of this is good, say you have a Service() which wraps up all the logic and is then implemented in an app, a web site, a windows service etc. When you start wrapping that service in another service, in another service I think its time to take a step back and see if you cant just instantiate the lower level services you need directly and call them in one layer

Body:
I take it you have something like this?

public class Main(string[] args)
{
    string param = args[0]; //load parameter from config
    Classifier c = new Classifier(param)

    SomeClass x = new SomeClass(c);
    var o = x.DoSomething();
}

public class SomeClass
{
    OtherClass o;

    //doesnt use the classifier but needs it for OtherClass,
    //hence required for passing down the chain
    public SomeClass(Classifier c)
    {
        o = new OtherClass(c);
    }

    public object DoSomething()
    {
        return o.DoSomthing();
    }
}

public class OtherClass
{
    public OtherClass(Classifier c) {} //uses classifier object 'far away'

    public object DoSomething() {}
}

And you want to avoid either having the Classifier object passed through ever constructor in the chain, or having objects which arent the actual application reading from the config directly?

My Suggestion in these cases it that you can do one of two things

A: Check that your 'higher in the chain classes' are obeying the single responsibility principle. Would it be better just to call OtherObject directly?

B: Can you move the injected parameter to be a parameter of the function call? in this case x.DoSomething(c);

In most cases I think it is a code smell. If you code is too 'deep' in this way its likely that your objects don't just do one thing anymore but orchestrate various other classes to do multiple things. Although one layer of this is good, say you have a Service() which wraps up all the logic and is then implemented in an app, a web site, a windows service etc. When you start wrapping that service in another service, in another service I think its time to take a step back and see if you cant just instantiate the lower level services you need directly and call them in one layer


问:
Is there such a thing as the testing of automation?
I know that it's possible perform automation of testing. That is, take tests that are manual, and make them automatic.

However, is there such a thing as the testing of automation? That is, checking if an automation process is working correctly or not?

I came across a job ad talking about "testing automation", and I'm 95% sure it means the automation of testing, but I wanted to check whether the testing of automation is a thing.

答:
Of course it's a thing (it's just unsearchable, because search engines don't handle meaningful differences in word order well).

Automation is code that does things you would otherwise have to do by hand. Spoken loosely, that covers all computer programs, so we usually use it to mean "code that generates other computer-readable assets". And of course it's testable - the same principles of unit testing apply as everywhere else.

Example: If your code generates images, you specify properties of the images you want, e.g. "this image has the same color balance as the other, but is smaller and lower-resolution".  If it's log files, you run it and then verify that the log contains the info you wanted to log. And if the output is other computer programs, you an either analyse them statically (without running them) or dynamically (by running them and testing their output). By definition, if that output is satisfactory, then the automation was successful, and that's what you want to ensure.


问:
Is executing SQL through a WebService a really bad idea?
Typically when creating a simple tool or something that has to use a database, I go through the fairly long process of first creating a webservice that connects to a database then creating methods on this webservice that do all the type of queries I need.. methods like

```<code>List<Users> GetUsers()
{
    ...
}
User GetUserByID(int id)
{
    ...
}
//More Get/Update/Add/Delete methods
</code>```

Is it terrible design to simply make the webservice as secure as I can (not quite sure the way to do something like this yet) and just make a couple methods like this

```<code>SqlDataReader RunQuery(string sql)
{
     ...
}

void RunNonQuery(string sql)
{
     ...
}
</code>```

I would sorta be like exposing my database to the internet I suppose, which sounds bad but I'm not sure.

I just feel like I waste so much time running everything through this webservice, there has to be a quicker yet safe way that doesn't involve my application connecting directly to the database (the application can't connect directly to database because the database isn't open to any connections but localhost, and where the appliction resides the standard sql ports are blocked anyway)

Especially when I just need to run a few simple queries

答:
You don't say anything about what kind of 'simple tools' you are talking about, so you just get knee-jerk answers based on what people assume it to be.

If the tools are desktop apps distributed to untrusted users over the internet, then obviously it would be an incredible bad idea to allow them to execute arbitrary sql on your database server. On the other hand if the tool is an admin tool run by yourself or a webapp running on an trusted server then it could be fine to cut out the middleman and call directly to the database. So the answer is: It depends!

In any case, you solution seem kind of half baked. If you don't trust the clients enough to give them a direct database connection, then you shouldn't allow them to execute arbitrary SQL either. If your sysadmin disabled database connections for security reasons, then you should probably not try to circumvent this by "tunneling" arbitrary SQL through a web service.


答:
.net provides ">SortedList class in System.Collections.Generic which keeps the list sorted. Your TKey class will need to implement IComparable, or you will need to implement an Comparer for TKey.

If my class was to be sorted in the same way each time, then I would implement IComparable, but if I wanted sometimes to sort on same A then B, but other times say C then A I would write Comparer's and pass then to SortedList.

SortedList is great if you have a large collection that you need to check to see if a key exists in - List can become very slow for these kinds of operations. However, SortedList will be slower to insert values into.

Title: Generic Sorting of Lists<>

Body:
I have several Lists<> that holds objects of different classes.

```<code>List<classA> listA;
List<classB> listB;
List<classC> listC;
//...
List<classM> listM;
</code>```

The classes do not relate in any way and have nothing in common except that they might have a single property marked with an Attribute SortBy=true

```<code>    [CustomObjectComparerAttribute(IncludeInCompare = true, Title = "View Order", SortBy=true)]
    public int ViewOrder { get; set; }
</code>```

What I would like to do is to have a generic function that accepts a list of any sort. This is problem Nr 1, because I can not figure out a way to make a function accept Lists<> of different types.

```<code>private List<object> SortList(List<object> aList)  //<-- this is not allowed (problem 1)
{
    //Get which property we sort by...
    PropertyInfo  prop = GetPropertyToSortBy(objectA);

    //Sort the list
    //Problem Nr 2: How do I get `PropertyInfo prop` in the statement below
    List<Order> SortedList = aList.OrderBy(o=>o.ThePropToSortBy).ToList();
}
    private PropertyInfo GetPropertyToSortBy(object o)
    {
        Type t = o.GetType();
        foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (Attribute.IsDefined(prop, typeof(CustomObjectComparerAttribute)) && ((CustomObjectComparerAttribute)Attribute.GetCustomAttribute(prop, typeof(CustomObjectComparerAttribute))).SortBy == true)
            {
                return prop;
            }
        }
        return null;
    }
</code>```

I feel that Im attacking this problem from the wrong angle. Am I on the right track?, and if so, how can I solve my problems?

if not, can you point me in the right direction?

Body:
.net provides SortedList class in System.Collections.Generic which keeps the list sorted. Your TKey class will need to implement IComparable, or you will need to implement an Comparer for TKey.

If my class was to be sorted in the same way each time, then I would implement IComparable, but if I wanted sometimes to sort on same A then B, but other times say C then A I would write Comparer's and pass then to SortedList.

SortedList is great if you have a large collection that you need to check to see if a key exists in - List can become very slow for these kinds of operations. However, SortedList will be slower to insert values into.


答:
Test Automation is the process of automating testing, you guessed correct.

However, your misunderstanding is actually the more interesting question: can you test automation? Well, it turns out that the question isn't so interesting after all: an automation script is just another program, so you can test it like any other program. Okay, sure, its primary purpose is to have a side-effect (say restarting a server, updating a software package, etc., editing a config file), and it interacts with an environment largely outside of its control (server daemons, computers on another network, the filesystem, the OS), both of wich make it harder to test than a pure function, but it's testable nonetheless.

Title: Is there such a thing as the testing of automation?

Body:
I know that it's possible perform automation of testing. That is, take tests that are manual, and make them automatic.

However, is there such a thing as the testing of automation? That is, checking if an automation process is working correctly or not?

I came across a job ad talking about "testing automation", and I'm 95% sure it means the automation of testing, but I wanted to check whether the testing of automation is a thing.


问:
Reading file during write on linux
As I understand, when a file is being written, the process writing to the file obtains an exclusive lock. So other processes cannot access this file for read.

With the above knowledge, I'm unable to understand how I'm able to play a video in media player, when the browser is still downloading it.

答:
The files usually aren't locked - unix file locking.  It is also fairly common to have multiple readers of file but only one writer.  Problems only occur when you would have multiple writers.

Also, most videos file formats (and especially on the web) are streamable, which means that you don't have to have the whole video to play it.

Title: Reading file during write on linux


答:
Your understanding is wrong. Several Linux processes can write to the same file at once (and what happens then might be unspecified, except when the processes overwrite different segments of that file). And some other Linux process (e.g. your browser) can read a file which is written to.

You could adopt a convention to avoid that. For example, you could use advisory file locking (adopting the convention that every relevant program should do that), e.g. with flock(2), lockf(3), etc.... But that won't forbid other processes (not following your conventions) to access (or even write to) that file. You might use permission machinery (e.g. by dedicating a system user to your setuid program).

See also this & that answers on StackOverflow (some of them mentioned the deprecated mandatory locking Linux-specific mechanisms). Read about ACID properties, consider using some database (sqlite, PostGreSQL, MongoDB, etc...) or some indexed file (gdbm).

I don't know Windows, but heard the rumor that it does not allow concurrent access or writes to the same file.

Title: Reading file during write on linux

Body:
As I understand, when a file is being written, the process writing to the file obtains an exclusive lock. So other processes cannot access this file for read.

With the above knowledge, I'm unable to understand how I'm able to play a video in media player, when the browser is still downloading it.


问:
Is Logger.getLogger(MyClass.class) the best way to initialise log4j loggers?
This Mkyong tutorial suggests intialising loggers this way:

```<code>@Controller
public class WelcomeController {

    private static final Logger logger = Logger.getLogger(WelcomeController.class);

   // etc

}
</code>```

Now presumably every other class you use, that has a logger will initialise their loggers the same way.

My question is - is this the best way to do it? It seems... repetitive.

答:
Your comment says that "verbose" refers to the need to repeat this line of code in every class. My first response is that, in the big picture, adding two lines of code (variable definition plus import statement) to every class isn't that big a deal. Especially since you only need to add them to the classes that have behavior and therefore need to do logging. That said, the specific line of code that you're using is prone to copy-paste errors (more on that later).

But, since you want alternatives, here are a few, with reasons that you might or might not want to use them.

Use a single logger for the entire app

If you don't care about what class is reporting, or are willing to put all necessary context into the message, than a simple singleton logger will do the job:

```<code>LoggerSingleton.getInstance().debug("MyController is running")
</code>```

In my opinion, one of the big benefits of a logging framework is having the context provided by separate logger instances -- if only to direct the log messages to different destinations. I wouldn't give that up just to save one line of code (you still need the import).

Plus, this increases verbosity at the point of use, which will end up in far more keystrokes.

Create your loggers at the point of use

I'm throwing this one out just because it eliminates the variable. I don't think I need to comment on it. Although it does show my preferred technique for getting a logger instance.

```<code>Logger.getLogger(getClass()).debug("blah blah blah");
</code>```

Use a bean post-processor to inject the logger

Your example uses Spring, and Spring lets you hook into the bean initialization code. You could create a post-processor that inspects the bean for a logger member variable, and creates a Logger instance when it finds one.

While such a post-processor is only a few dozen lines of code, it's another moving part in your application, and therefore another potential source of bugs. I prefer to have as few of those as possible.

Use a mixin

Scala and Groovy provide traits, which let you encapsulate behavior. A typical Scala pattern is to create a Logging trait, then add it to the class that needs logging:

```<code>class MyController with Logging
</code>```

Unfortunately, this means that you have to switch languages. Unless you're using Java 8, in which case you can create a Logging interface with a "default method":

```<code>public interface Logging {
    default Logger getLogger() {
        return Logger.getLogger(getClass());
    }
}
</code>```

Now, within your class code, you can simply use

```<code>getLogger().debug("blah blah blah");
</code>```

While easy, this has a couple of disadvantages. For one thing, it pollutes the interface of every class that uses it, because all interface methods are public. Perhaps not that bad if you use it only for classes that are instantiated and injected by Spring, especially if you follow interface/implementation separation.

The bigger problem is that it has to look up the actual logger instance on every call. Which is fast, but unnecessary.

And you still need an import statement.

Move logger to a superclass

I'll repeat: I don't find repeated logger definitions verbose, but if you do I think this the best approach to eliminating them.

```<code>public abstract class AbstractController {
    protected Logger logger = Logger.getLogger(getClass());
}
</code>```

Now your controller classes inherit from AbstractController, and they have access to the logger variable. Remember that you have to put the @Controller annotation on the concrete class.

Some people will find this a perversion of inheritance. I have tried to mollify them by naming the class AbstractController rather than AbstractProjectClass. You can decide for yourself whether or not there's an is-a relationship.

Other people will object to the use of an instance variable rather than a static variable. IMO static loggers are prone to copy-paste errors, because you have to explicitly reference the classname; getClass() ensures that your logger is always correct.

Body:
Your comment says that "verbose" refers to the need to repeat this line of code in every class. My first response is that, in the big picture, adding two lines of code (variable definition plus import statement) to every class isn't that big a deal. Especially since you only need to add them to the classes that have behavior and therefore need to do logging. That said, the specific line of code that you're using is prone to copy-paste errors (more on that later).

But, since you want alternatives, here are a few, with reasons that you might or might not want to use them.

Use a single logger for the entire app

If you don't care about what class is reporting, or are willing to put all necessary context into the message, than a simple singleton logger will do the job:

LoggerSingleton.getInstance().debug("MyController is running")

In my opinion, one of the big benefits of a logging framework is having the context provided by separate logger instances -- if only to direct the log messages to different destinations. I wouldn't give that up just to save one line of code (you still need the import).

Plus, this increases verbosity at the point of use, which will end up in far more keystrokes.

Create your loggers at the point of use

I'm throwing this one out just because it eliminates the variable. I don't think I need to comment on it. Although it does show my preferred technique for getting a logger instance.

Logger.getLogger(getClass()).debug("blah blah blah");

Use a bean post-processor to inject the logger

Your example uses Spring, and Spring lets you hook into the bean initialization code. You could create a post-processor that inspects the bean for a logger member variable, and creates a Logger instance when it finds one.

While such a post-processor is only a few dozen lines of code, it's another moving part in your application, and therefore another potential source of bugs. I prefer to have as few of those as possible.

Use a mixin

Scala and Groovy provide traits, which let you encapsulate behavior. A typical Scala pattern is to create a Logging trait, then add it to the class that needs logging:

class MyController with Logging

Unfortunately, this means that you have to switch languages. Unless you're using Java 8, in which case you can create a Logging interface with a "default method":

public interface Logging {
    default Logger getLogger() {
        return Logger.getLogger(getClass());
    }
}

Now, within your class code, you can simply use

getLogger().debug("blah blah blah");

While easy, this has a couple of disadvantages. For one thing, it pollutes the interface of every class that uses it, because all interface methods are public. Perhaps not that bad if you use it only for classes that are instantiated and injected by Spring, especially if you follow interface/implementation separation.

The bigger problem is that it has to look up the actual logger instance on every call. Which is fast, but unnecessary.

And you still need an import statement.

Move logger to a superclass

I'll repeat: I don't find repeated logger definitions verbose, but if you do I think this the best approach to eliminating them.

public abstract class AbstractController {
    protected Logger logger = Logger.getLogger(getClass());
}

Now your controller classes inherit from AbstractController, and they have access to the logger variable. Remember that you have to put the @Controller annotation on the concrete class.

Some people will find this a perversion of inheritance. I have tried to mollify them by naming the class AbstractController rather than AbstractProjectClass. You can decide for yourself whether or not there's an is-a relationship.

Other people will object to the use of an instance variable rather than a static variable. IMO static loggers are prone to copy-paste errors, because you have to explicitly reference the classname; getClass() ensures that your logger is always correct.


问:
Is N-Tier worth it when developing an ASP.NET application?
Let me start of by saying that by "worth it" I don't mean "remove DI and interfaces" and such.

What I mean is to place the code in separate class libraries. Like done in the Onion architecture - which I like very much.

The problem is that the ASP.NET project is the bootstrapper when it really it should just do web presentation stuff.
It gets even worse when using Identity because the ApplicationUser class is tightly coupled with Entity Framework. Because now your Core depends on EF. Which is not what N-Tier is all about.

So my question is. Is separating code into different class libs worth it when doing ASP.NET?

答:
Separating code into class libraries (ie. seperate assemblies) can improve design because you can manage dependencies clearly - eg. you can ensure the frontend have a reference to the data access layer but not the other way around. .Net allows circular dependencies between classes, but not between assemblies, and circular dependencies between layers should be avoided. There is no big cost to creating several projects in VS, so I would say it is definitely worth it.

But this is not n-tier architecture. The tiers in n-tier are physically separated (on different servers) and communicate over network. Of course this introduces additional complexity since each layer needs a service interface and network stack etc., so this is only worth it if you have specific requirements like the ability for separate independent frontends to access the same business logic layer.


答:
People are not really criticizing just telling you it is not a good idea.

WCF is an alternative.

It is not like exposing the database to the internet - it is exposing the database to the internet.  Ports are locked down for a reason.  It is not just a security risk in general but clearly you would be violating your security policy.  The person / group that locked those ports would be very unhappy with you.

As for "Especially when I just need to run a few simple queries"

Nothing saying you cannot have general method

```<code>void RunNonQuery(Int id)
{
     ...
}
</code>```

Maybe not the best design but at least you are not passing  SQL

With WCF I think you can return a DataTable and SqlDataReader so you could do like

```<code>SqlDataReader RunQuery(Int id)
{
     ...
}
</code>```

Again maybe not the best design but it is secure

Lets say there was no sensitive data you could have a read only connection  with a short timeout to protect against denial of service attacks

```<code>SqlDataReader RunQuery(String SQL)
{
    ...
}
</code>```

But I seriously doubt you would get that past the security people

If you want to do something like that for sure get it approved by security

You don't want someone to just find out you are doing that

You need to get permission up front

Simple tool or something that has to use a database

Is it just a database

If the data does not need to be shared then consider an embedded database

Does the tool need to be desktop app?  Can it be web app?

Title: Is executing SQL through a WebService a really bad idea?

Body:
Typically when creating a simple tool or something that has to use a database, I go through the fairly long process of first creating a webservice that connects to a database then creating methods on this webservice that do all the type of queries I need.. methods like

```<code>List<Users> GetUsers()
{
    ...
}
User GetUserByID(int id)
{
    ...
}
//More Get/Update/Add/Delete methods
</code>```

Is it terrible design to simply make the webservice as secure as I can (not quite sure the way to do something like this yet) and just make a couple methods like this

```<code>SqlDataReader RunQuery(string sql)
{
     ...
}

void RunNonQuery(string sql)
{
     ...
}
</code>```

I would sorta be like exposing my database to the internet I suppose, which sounds bad but I'm not sure.

I just feel like I waste so much time running everything through this webservice, there has to be a quicker yet safe way that doesn't involve my application connecting directly to the database (the application can't connect directly to database because the database isn't open to any connections but localhost, and where the appliction resides the standard sql ports are blocked anyway)

Especially when I just need to run a few simple queries

Body:
People are not really criticizing just telling you it is not a good idea.

WCF is an alternative.

It is not like exposing the database to the internet - it is exposing the database to the internet.  Ports are locked down for a reason.  It is not just a security risk in general but clearly you would be violating your security policy.  The person / group that locked those ports would be very unhappy with you.

As for "Especially when I just need to run a few simple queries"

Nothing saying you cannot have general method

void RunNonQuery(Int id)
{
     ...
}

Maybe not the best design but at least you are not passing  SQL

With WCF I think you can return a DataTable and SqlDataReader so you could do like

SqlDataReader RunQuery(Int id)
{
     ...
}

Again maybe not the best design but it is secure

Lets say there was no sensitive data you could have a read only connection  with a short timeout to protect against denial of service attacks

SqlDataReader RunQuery(String SQL)
{
    ...
}

But I seriously doubt you would get that past the security people

If you want to do something like that for sure get it approved by security

You don't want someone to just find out you are doing that

You need to get permission up front

Simple tool or something that has to use a database

Is it just a database

If the data does not need to be shared then consider an embedded database

Does the tool need to be desktop app?  Can it be web app?


答:
Unix OSes do not use compulsory locking (Gnu/Linux is a Unix, other examples are UNIX, BSD, Mac OSX). Locking as avoided where ever possible.

Some other OSes use compulsory locking all the time (Notably Microsoft's Windows OS). This will stop you playing until fully downloaded, it will also stop you renaming a file or directory that is open (that an application is in). But on Unix it is OK. If an application needs locking it can use it. But not normally.

Title: Reading file during write on linux


问:
What are your decision critera in C++ to make something a data member or virtual method?
(Figured this was too subjective for SO, so posting here...)

I have some behavior that I can implement in various ways.  At least two methods are shows in the code snippet below.  Presume that the m_well data member is correctly set somehow at object construction time.

```<code>struct Behavior
{
    virtual bool behavesWell() { return true; }

private:
    bool m_well;
public:
    bool behavesMemberWell() { return m_well; }
};

struct OtherBehavior : public Behavior
{
    virtual bool behavesWell() { return false; }
};
</code>```

Obviously the one relies upon virtual dispatch, and the other merely the return of a data member.

A third, non-shown method would likely have the non-virtual public member function not return a fixed data member, but instead call a virtual - lets leave that aside for the purpose of this please.

What would lead you to one or other other of these two methods of implementing functionality, such that a user of this class can interrogate an object's behavior?

答:
virtual bool behavesWell() incurs extra processing overhead but, usually, it's a nonissue (e.g. Virtual functions and performance - C++).

bool behavesMemberWell() has extra storage requirements: you have an extra bool m_well in every object you create. With the first approach you just have an additional pointer in the vtable (once per class).

If the Behavior class can have more than one virtual function, I'd prefer the first approach (virtual function).


问:
How to change the same code stored in several places after I improve one of them?
I have some code written in Matlab. I use the code in different folders which contains different data. Because I want to change some parameters for each different data, I keep the code in the folder of each data to remember what parameters I have used.

The problem is that sometimes I improve the code and it is hard to go to each folder and change that part of code. Is there any solution to this problem? It would be good if I change some part of the code then it changes in all other places I have stored the same code.

Would version control help with this problem?

答:
Version control isn't what you need here. You need to put your code which lives in many places in a single place.

A good first step would be to create a folder for your shared code, copy the shared code into functions in that shared folders, and replace the original copies with function calls to the code in the shared folder.

Here is the documentation to get you started with authoring functions:
http://www.mathworks.com/help/matlab/function-basics.html

For the original files to be able to find the new functions in the new shared folder, you'll need to add that new folder to your MATLAB search path. more information is here:
http://www.mathworks.com/help/matlab/search-path.html

OwnerDisplayName: yashar


问:
Mnemonic for always overriding equals when you override hashCode?
We java developers always know that you should always override equals() when you override hashCode(), but I consistently have trouble remembering this rule.

What is a clever mnemonic to help Java developers remember this?

答: It is interesting that no one has pinpointed that OP' assumption that one has to override equals() when hashCode() is overridden is completely false. Though the opposite holds true - when equals() is overridden you have to override hashCode() as well. The mnemonic is very easy, just use the first letter of each method.  equals() is before hashCode() in the English alphabet so - "if e then h".