问:
What's the alternative to DRY code when it requires too many parameters?
What is the best strategy for maintaining easy to follow code when keeping things DRY means you have to pass a lot of parameters to shared functions?

In my specific case, I have a grails based app, and have implemented a system where to reference object B from object A,  I have taglibs, gsp's, javascript and service code to manage that allows the user to click a link, a list of all object B's popup, allow them to select or Add a new 'B' entry and that reference then gets stored in a field in object A,
This is being implemented in many different places, parameterising many things.

Keeping this DRY is becoming a bit of a nightmare to maintain, and certainly difficult for any new eyes to understand.

答:
The usual advice to avoid repeating the same set of parameters over and over again is to turn parameters that only appear together into a class, and pass an object of that class instead of a list of values. It's perfectly okay to create a class type that merely serves to make your code drier that way.

You sound as if you have the added constraint that the same set of parameters have to flow through code written in different languages. That makes things more difficult, but as long as these values keep appearing together it's often feasible to write that structure down once and then auto-generate classes/structures in different languages from that single declaration. You'd need to post more details about your system to decide whether that's possible, or worthwhile.


答:
Without seeing any code, it's difficult to give precise advice for your situation. However, your situation is likely highlighting how DRY is the enemy of KISS and loose coupling. To reduce duplication, you have created a set of shared functions. Those functions need many parameters and likely are used in many places. So they are now more complex than they could have been if code were repeated and couple many parts of your application to those functions.

DRY is not a hard-and-fast rule. It's one of many guidelines to creating better code. It needs to be balanced against other conflicting guidelines though. If a little repetition reduces complexity and coupling, then opt for a little repetition.

ContentLicense: CC BY-SA 3.0

Title: What's the alternative to DRY code when it requires too many parameters?

Body:
What is the best strategy for maintaining easy to follow code when keeping things DRY means you have to pass a lot of parameters to shared functions?

In my specific case, I have a grails based app, and have implemented a system where to reference object B from object A,  I have taglibs, gsp's, javascript and service code to manage that allows the user to click a link, a list of all object B's popup, allow them to select or Add a new 'B' entry and that reference then gets stored in a field in object A,
This is being implemented in many different places, parameterising many things.

Keeping this DRY is becoming a bit of a nightmare to maintain, and certainly difficult for any new eyes to understand.


问:
How to generate learning material from your work
Catalyst: Recently my team has been tasked with bringing in house a large software project that has been worked on for over 20 years. Some of the old development team is still around, and originally the plan was to have them mentor us and bring us up to speed. After quick investigation, it's been determined that this project suffers from the following:

No testing framework. Everything is manually tested at an integration level and shipped off to the customer to verify the changes.

No up-to-date design documentation.

Limited learning material. The code does a lot of non-standard things(lots of use of configuration files that define business behavior, use of multiple configuration files for GUI [attributes of the GUI can be set in file A.extenion_x or B.extension_y, but not real clear as to why])

What I'm trying to come up with is a list of things our developers can do as they work in order to teach other members of the team, or future members of the team. Basically I just want them to document their learning, and then archive that information.

Luckily the project did take advantage of issue tracking software, so each bugfix or feature change can be tied to a unique identifier. We can then archive the learning material and tie it together with the same id. An example of said learning material, would be a quick write up about the change, a test plan, and other applicable information for the change.

Outside of making use of unit testing (that's the goal, but it's not going to be able to be completed in the short term), what are some other ways we can generate learning documentation as part of our development process.

答:
First of all, you hit the nail on the head: Michael Feathers drives home the point time after time that legacy code is code without unit tests, and this must be priority one when working in legacy projects.

Aside from that, you also bring up issue trackers. I am not sure that they are useful in the context of training and documentation.

I would focus on the architecture. Any project large enough to warrant this amount of effort will have some high-level design consisting of modules (unless it truly is a big ball of spaghetti).

I would have a two-prong approach:

The senior members of the legacy team who know the product need to come up with high-level documentation describing the key points of the software from the perspective of a developer working on the software. This should be very concise, and precisely as long as it needs to be. It should be written such that a developer new to the project has enough context to get started, but is not overwhelmed and drowning in documentation.

Your developers that are taking over the project need to document each non-trivial issue they encounter and how they solved it. They are fresh eyes who are not intimately familiar with the software: odds are if they are tripped up by something, so will someone else. Ideally this would tag on with the previous documentation: a legacy developer documents module XYZ at a high level, and the new developers add in their own lessons learned from dealing with the module, editing it all into one cohesive (and concise!) document.

The end goal should be a concise but useful document that can bring developers up to speed on the software product.

I would probably stuff the documentation into a MediaWiki or something similar to it.


问:
How to represent very specific business logic in classes containing the business logic?
BusinessModel: I have a ice cream shop and I designed classes to do my supplier based financials based on industry types(Lines of business). I sell ice creams of many types, which I buy from different suppliers, and at the end of the month I try to reconcile my account by line of business using classes I created for cost calculation purposes. The method ProcessFile contains the algorithm specific to LOB calculation.

I am trying to think about a proper way to tackle this problem. However, I am running into a problem with naming classes and not exactly sure what design pattern perspective to use. I'd like a solution which is a engine - it gets input, does processing and produces an output.

Here is my interface to start with.

```<code> public interface IFileProcessing
    {
    string InputFilePath { get; set;}
    string OutputFilePath { get; set;}
    string ProcessedFilePath { get; set; }
    string ExtractionFieldsFromWebService{ get; set; }
    void ProcessFile(string FileName, string FilePath);
    }
</code>```

All this is happening based on 5 different models(line of businesses), aka classes I defined. Lets say for example,  My classes handle my calculation of my costs

```<code>public class IceCreamLOB : IFileProcessing
public class FrozenCustardLOB : IFileProcessing
public class GelatoLOB: IFileProcessing
public class FrozenCustard: IFileProcessing
</code>```

So far everything is generic to the line of businesses mentioned above. The complexity comes when I am being asked to design classes specifically for suppliers, aka example, BreyersLOB, or KlondikeLOB, which is say my biggest account and these accounts need special processing specifics.

I don't know if I should be naming my classes specific to supply vendors.

My questions are all related to this:

How can I maintain logical processing specific to a supplier in a class without naming the class a specific vendor? Is there a good pattern when you come across a situation like this?

How would I go about scaling this without using inheritance, or do I need to use it?

What situations should name your classes specific to the vendor/business partner you work with? Like in my example, KlondikeLOB and BreyersLOB

答:
Could do with a bit more info on what process file is doing. But I think your problem may be in conflating the processing method with the line of business, or product type.

presumably we have some generic file processing methods, converting lines from whatever file format into product purchases or sales, then some processing working out financials on those purchases/sales.

I would split these two, into file processing, which would have input of file format X, say supplier specific csv and output purchase/sale records to a generic format/database.

eg

```<code>CSVFileProcessor : IFileProcessor
DATFileProcessor : IFileProcessor
KlondikeCustomFileProcessor :IFileProcessor
</code>```

Then have ledger processing, which would have those records as input and output reports, invoices, payments whatever.

eg.

```<code>IceCreamProfits : ILedgerReport
KlondikeSales : IInvoiceCreator
</code>```

You would record the supplier and lob in the ledger record, so your secondary process is able to only look at suppliers X or Y or lob A or B if required

OwnerDisplayName: Jeff Jaffery

Body:
Could do with a bit more info on what process file is doing. But I think your problem may be in conflating the processing method with the line of business, or product type.

presumably we have some generic file processing methods, converting lines from whatever file format into product purchases or sales, then some processing working out financials on those purchases/sales.

I would split these two, into file processing, which would have input of file format X, say supplier specific csv and output purchase/sale records to a generic format/database.

eg

CSVFileProcessor : IFileProcessor
DATFileProcessor : IFileProcessor
KlondikeCustomFileProcessor :IFileProcessor

Then have ledger processing, which would have those records as input and output reports, invoices, payments whatever.

eg.

IceCreamProfits : ILedgerReport
KlondikeSales : IInvoiceCreator

You would record the supplier and lob in the ledger record, so your secondary process is able to only look at suppliers X or Y or lob A or B if required


问:
Await state async
For speed we sometimes return response to consumer before state is saved in DB. Sometimes (Mostly for our automated consumers) this can break because the want to make actions on the saved data before it is saved. I wrote this little helper

```<code>public async Task<TEntity> GetWithRetry<TEntity>(Expression<Func<TEntity, bool>> predicate, string errorOnTimeout) where TEntity : class
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    do
    {
        var entity = await _context.DbSet<TEntity>().FirstOrDefaultAsync(predicate);
        if(entity == null)
            await Task.Delay(100);
        else
            return entity;
    } while(stopwatch.Elapsed < TimeSpan.FromSeconds(1000));

    throw new Exception(errorOnTimeout);
}
</code>```

Used like

```<code>var existingBooking = await GetWithRetry<Booking>(b => b.BookingKey == confirmCommand.BookingKey, "Booking key not found");
</code>```

Any pitfalls? Task.Delay should scale well since it returns the thread to the pool, and if the data exists in DB the first time around it should not give much more overhead than an extra wrapped task?

This is the current version of the code:

```<code>public async Task<TEntity> FirstAsync<TEntity>(Expression<Func<TEntity, bool>> predicate, string errorOnTimeout, TimeSpan? timeout = null) where TEntity : class
{
    var entity = await FirstAsyncOrDefault(predicate, timeout);
    if(entity != null) return entity;

    throw new Exception(errorOnTimeout);
}

public async Task<TEntity> FirstOrDefaultAsync<TEntity>(Expression<Func<TEntity, bool>> predicate, TimeSpan? timeout = null) where TEntity : class
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    if(timeout == null)
        timeout = TimeSpan.FromSeconds(1);

    do
    {
        var entity = await DbSet<TEntity>().FirstOrDefaultAsync(predicate);
        if(entity != null) return entity;

        await Task.Delay(100);

    } while(stopwatch.Elapsed < timeout);

    return null;
}
</code>```

答:
In my experience retries like this are a bad idea.

Reasoning:

They make you code inherently non deterministic. How many times will you hit the db? if you got null back do you just need to wait longer or is there a problem?

They introduce a performance problem. If you have some process which calls this function it potentially takes timeout milliseconds to complete.

Threading issues. if you are performing multiple operations, say web requests, each will spawn on of these loops. if the timeout takes longer than the frequency of requests everything will grind to a halt.

If you want to do something once and event has occurred, you should have an event which triggers the process.

you can do this by having a queue of tasks and a worker process, or if its all in the same code, just .ContinueWith(NextStep)

Title: Await state async


答:
TL;DR: encapsulate the common arguments or save state using partial application or object instantiation.

In the abstract if you want to reduce the number of arguments passed to functions and many of those arguments recur then you can use encapsulation. This can take the form of a data structure (list, hash map, etc). If there is high cohesion between the data and the functions you can also create a class where the functions are methods.

Alternatively, if the arguments are built up over different logical blocks or over time, you can use partial application. This would also allow reuse depending on the how long the data is valid.  For example if some data is determined at start up of the application and rarely changes I could use partial application and reuse the resulting function until it does change. If you call many different functions with many of the same arguments you could leverage compose and partial application to manage the code complexity.

FYI: there are certainly other ways of solving this that may work better for you specific example. For example, you may even want to use a Singleton, globals, class variables, etc. There will be different costs and benefits to any code organization technique. Use whatever gives you the smallest implementation that is extensible, maintainable and readable.


问:
Should I stop using the term C/C++?
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

Should I stop using the term C/C++?

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these questions so I'm very interested to get good answers especially for the points that have to do with the C++ tendency in the near future.

答:
C/C++ is the intersection of C and C++.

int new; is not C/C++, and neither is vector<int> foo;.

Similarly, C89/C99 is the intersection of these two languages, where neither enum bool { false, true }; or for(int i = 0;;) is allowed.

And C++11/C++14, etc.

It is possible to write code that compiles (and correctly runs) under C++11 and C++14, even though compiling under one doesn't imply it compiles under the other. In fact, a lot people do this.

And a lot of people write code that works in C and C++.

Obviously, the greater the overlap, the more sense it makes; I don't expect to see any questions about C/C++/Java code.

Though it does "make sense" to talk about a common subset of these languages, many questions will not have answers in this subset, e.g. What should main() return in C and C++?

But you can talk about code that works for multiple language specifications, whether those specs are differentiated by "version" or "language name" or otherwise.

OwnerDisplayName: redobot

Title: Should I stop using the term C/C++?


答:
The programming language Haskell actually had a similar problem with its "record syntax" for data structures, where you would potentially be updating the third field of a data structure with things like:

```<code>incrementCount MyRecord{param1=p1, param2=p2, count=c, param3=p3} = MyRecord{
        param1=p1, param2=p2, count=c+1, param3=p3}
</code>```

This was solved by adding some language-level syntactic features which look more like updating a dictionary:

```<code>incrementCount m@MyRecord{count=c} = m{count = c + 1}
</code>```

Here the m@<pattern> syntax now supports a "partial pattern" and the count parameter in the record can be specifically referenced and updated. One of the biggest problems that this solves is that you no longer have to update every single function which handles the data structure, merely because you have updated the definition of the data structure to, say, rename key parameters or add new ones.

You can do this too! You just need to pass all of the parameters as one shared parameter dictionary; instead of function (url, queryParams, handlingNotes, ...) you can start to standardize on a request object {url: u, queryParams: q, handlingNotes: h, ...}. Each function which handles the request object will only care about the narrow subset that it cares about and will pass the other parameters right on through, with no boilerplate code needed.

Body:
The programming language Haskell actually had a similar problem with its "record syntax" for data structures, where you would potentially be updating the third field of a data structure with things like:

incrementCount MyRecord{param1=p1, param2=p2, count=c, param3=p3} = MyRecord{
        param1=p1, param2=p2, count=c+1, param3=p3}

This was solved by adding some language-level syntactic features which look more like updating a dictionary:

incrementCount m@MyRecord{count=c} = m{count = c + 1}

Here the m@<pattern> syntax now supports a "partial pattern" and the count parameter in the record can be specifically referenced and updated. One of the biggest problems that this solves is that you no longer have to update every single function which handles the data structure, merely because you have updated the definition of the data structure to, say, rename key parameters or add new ones.

You can do this too! You just need to pass all of the parameters as one shared parameter dictionary; instead of function (url, queryParams, handlingNotes, ...) you can start to standardize on a request object {url: u, queryParams: q, handlingNotes: h, ...}. Each function which handles the request object will only care about the narrow subset that it cares about and will pass the other parameters right on through, with no boilerplate code needed.


问:
OO Pattern for making multiple versions of domain logic available to the client
I'm writing a PHP application where a block/module of domain logic is subject to frequent, significant changes over time.

The complication is the application needs to be able to use not just the latest version of the module, but any version that it has previously used, so it can reproduce the results of data that that version would have made.

I would use a facade and/or adapters or similar so the application's main code can switch between which versions of the module it uses without too much trouble.

As for the module, I was planning to use namespacing for each major revision (where the domain logic produces different results); duplicating all the classes in that domain logic module. I.e. effectively copy-and-paste the entire thing, including classes within the module that haven't changed.

This is a pungent code smell and I can't think of any way round it, let alone a simple way, given that the module may also undergo complete restructuring.

Any ideas?

答: Sounds like you need the strategy pattern. Basically, define an interface that all instances of your business logic can use, then invoke the proper instance (strategy) of the logic. Determination of what constitutes the "proper" instance is up to you, usually it's an attribute in the request header, but it could be contextual.</p>


问:
Which C# data structure should I use to quantify this information?
I am attempting to determine which data structure I should use for the following information:

```<code>        ("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, "");
        ("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, "");
        ("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, .084F, "");
        ("Cheese", 37F, 406F, 24F, .01F, .000F, .027F, .64F, 0F, 0F, .1F, "");
        ("Beef Sausage", 54F, 320F, 12F, .01F, .001F, .013F, .911F, 0F, .003F, .058F, "");
        ("Boiled Eggs", 75F, 155F, 12.5F, .01F, .001F, .010F, .124F, 0F, 0F, .373F, "");
        ("Broccoli", 89F, 34F, 3F, 2.4F, 0F, .021F, .033F, .089F, 0F, 0F, "");
</code>```

Essentially, these are types of food and certain constituent nutritional values and the string on the end is for additional comments.

I want to be able to call the name of the food elsewhere in the code
(i.e. NutritionalData("Tuna") and have it return the nutritional data previously stored in the data structure.

When replying, please bear in mind I am a novice programmer. I looked into Array but that seemed limited to one data type, and these need to be a combination of strings and floats. The first entry will be unique (there won't be two entries for "Tuna", for example), so I was wondering if the Dictionary data type might be best, but I don't know much about it.

Or would this be best as a new class like the following:

```<code>class FoodItem
    {
        string Name;
        float Hydration;
        float Calories;
        float Protein;
        float Fiber;
        float Iron;
        float Magnesium;
        float Sodium;
        float VitaminC;
        float Niacin;
        float Cholesterol;
        string Special;
    }
</code>```

Here is the edited code, Not sure if it works because I haven't figured out how to call a method from outside the class. Yay for self-education.

```<code>class MakeFoodDictionary
{
    public Dictionary<string, FoodItem> foodDictionary = new Dictionary<string, FoodItem>();

    public struct FoodItem
    {
        public string Name;
        public float Hydration;
        public float Calories;
        public float Protein;
        public float Fiber;
        public float Iron;
        public float Magnesium;
        public float Sodium;
        public float VitaminC;
        public float Niacin;
        public float Cholesterol;
        public string Special;
    }

    public FoodItem TempFoodItem;

    public void CreateAllFoods()
    {
        CreateNewFoodItem("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, "");
        CreateNewFoodItem("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, "");
        CreateNewFoodItem("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, .084F, "");
        CreateNewFoodItem("Cheese", 37F, 406F, 24F, .01F, .000F, .027F, .64F, 0F, 0F, .1F, "");
        CreateNewFoodItem("Beef Sausage", 54F, 320F, 12F, .01F, .001F, .013F, .911F, 0F, .003F, .058F, "");
        CreateNewFoodItem("Boiled Eggs", 75F, 155F, 12.5F, .01F, .001F, .010F, .124F, 0F, 0F, .373F, "");
        CreateNewFoodItem("Broccoli", 89F, 34F, 3F, 2.4F, 0F, .021F, .033F, .089F, 0F, 0F, "");
        CreateNewFoodItem("Dry Oats", 8F, 389F, 17F, 10.6F, .005F, .177F, .002F, 0F, .001F, 0F, "");
        CreateNewFoodItem("Ale", 91F, 37F, .2F, 0F, 0F, .007F, .013F, 0F, .001F, 0F, "Inebriation");
        CreateNewFoodItem("Salted Beans", 67F, 127F, 8.67F, 6.4F, .003F, .045F, .238F, .001F, .001F, 0F, "");
        CreateNewFoodItem("Bread", 32F, 278F, 8.4F, 6F, .003F, .081F, .346F, 0F, .004F, 0F, "");
        CreateNewFoodItem("Turnips", 92F, 28F, .9F, 1.8F, 0F, .011F, .067F, .021F, 0F, 0F, "");
        CreateNewFoodItem("Salted Pork", 11F, 748F, 5F, 0F, 0F, .007F, 2.684F, 0F, .002F, .086F, "");
        CreateNewFoodItem("Cabbage", 92F, 25F, 1F, 1.9F, 0F, .012F, .018F, .037F, 0F, 0F, "");
        CreateNewFoodItem("Dried Blueberries", 15F, 317F, 2.5F, 7.5F, .001F, .018F, .003F, .024F, .001F, 0F, "");
        //AddNewFoodToArray(string Name, float Hydration, float Calories, float Protein, float Fiber, float Iron, float Magnesium, float Sodium, float VitaminC, float Niacin, float Cholesterol);
        TempFoodItem = TempFoodItem;
    }

    public void CreateNewFoodItem(string _Name, float _Hydration, float _Calories, float _Protein, float _Fiber, float _Iron, float _Magnesium, float _Sodium, float _VitaminC, float _Niacin, float _Cholesterol, string _Special)
    {
        TempFoodItem = new FoodItem
        {
            Name = _Name,
            Hydration = _Hydration,
            Calories = _Calories,
            Protein = _Protein,
            Fiber = _Fiber,
            Iron = _Iron,
            Magnesium = _Magnesium,
            Sodium = _Sodium,
            VitaminC = _VitaminC,
            Niacin = _Niacin,
            Cholesterol = _Cholesterol,
            Special = _Special
        };
        foodDictionary.Add(_Name, TempFoodItem);
    }
}
</code>```

答:
Yes, use FoodItem.

You can store them in a List<>, then use linq (very cool) to find the one you want:

```<code>List<FoodItem> myFoodItems = new List<FoodItem>();

/* populate myFoodItems the hard way */
myFoodItems.Add(new FoodItem{
    Name = 'tuna',
    Hydration = 60F,
    /* rest of items skipped - you get the idea */
});

FoodItem tuna = myFoodItems.Find(e => e.Name == "tuna");
</code>```

If you have a zillion of FoodItems, you can also store them in a dictionary by name:

```<code>Dictionary<string, FoodItem> foodDict = new Dictionary<string, FoodItem>();
/* initialize the hard way */
myfoodItem = new FoodItem{
    Name = "tuna",
    Hydration = 60F,
    /* and so on */
};
foodDict.Add("tuna", myfoodItem);

FoodItem tuna = foodDict["tuna"];
</code>```

The duplication of FoodItem.Name and the key to the dictionary is OK - leave it there (it will save time debugging).

This is initializing the hard way - you really should store this data in a file somewhere then read it in when the program starts - that will make it easier to add new items and correct errors.  The code for that is much longer than this.

Body:
Yes, use FoodItem.

You can store them in a List<>, then use linq (very cool) to find the one you want:

List<FoodItem> myFoodItems = new List<FoodItem>();

/* populate myFoodItems the hard way */
myFoodItems.Add(new FoodItem{
    Name = 'tuna',
    Hydration = 60F,
    /* rest of items skipped - you get the idea */
});

FoodItem tuna = myFoodItems.Find(e => e.Name == "tuna");

If you have a zillion of FoodItems, you can also store them in a dictionary by name:

Dictionary<string, FoodItem> foodDict = new Dictionary<string, FoodItem>();
/* initialize the hard way */
myfoodItem = new FoodItem{
    Name = "tuna",
    Hydration = 60F,
    /* and so on */
};
foodDict.Add("tuna", myfoodItem);

FoodItem tuna = foodDict["tuna"];

The duplication of FoodItem.Name and the key to the dictionary is OK - leave it there (it will save time debugging).

This is initializing the hard way - you really should store this data in a file somewhere then read it in when the program starts - that will make it easier to add new items and correct errors.  The code for that is much longer than this.


答:
Go further</p>

```<code>public class NutritionalData
{
    public string Type {get;set;}
    public float Grams {get;set;}
}

public class FoodItem
{
   public string Name {get;set;}
   public List<NutritionalData> NutritionalContent {get;set;}
   public string Description {get;set;}
}
</code>```

Title: Which C# data structure should I use to quantify this information?

Body:
I am attempting to determine which data structure I should use for the following information:

```<code>        ("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, "");
        ("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, "");
        ("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, .084F, "");
        ("Cheese", 37F, 406F, 24F, .01F, .000F, .027F, .64F, 0F, 0F, .1F, "");
        ("Beef Sausage", 54F, 320F, 12F, .01F, .001F, .013F, .911F, 0F, .003F, .058F, "");
        ("Boiled Eggs", 75F, 155F, 12.5F, .01F, .001F, .010F, .124F, 0F, 0F, .373F, "");
        ("Broccoli", 89F, 34F, 3F, 2.4F, 0F, .021F, .033F, .089F, 0F, 0F, "");
</code>```

Essentially, these are types of food and certain constituent nutritional values and the string on the end is for additional comments.

I want to be able to call the name of the food elsewhere in the code
(i.e. NutritionalData("Tuna") and have it return the nutritional data previously stored in the data structure.

When replying, please bear in mind I am a novice programmer. I looked into Array but that seemed limited to one data type, and these need to be a combination of strings and floats. The first entry will be unique (there won't be two entries for "Tuna", for example), so I was wondering if the Dictionary data type might be best, but I don't know much about it.

Or would this be best as a new class like the following:

```<code>class FoodItem
    {
        string Name;
        float Hydration;
        float Calories;
        float Protein;
        float Fiber;
        float Iron;
        float Magnesium;
        float Sodium;
        float VitaminC;
        float Niacin;
        float Cholesterol;
        string Special;
    }
</code>```

Here is the edited code, Not sure if it works because I haven't figured out how to call a method from outside the class. Yay for self-education.

```<code>class MakeFoodDictionary
{
    public Dictionary<string, FoodItem> foodDictionary = new Dictionary<string, FoodItem>();

    public struct FoodItem
    {
        public string Name;
        public float Hydration;
        public float Calories;
        public float Protein;
        public float Fiber;
        public float Iron;
        public float Magnesium;
        public float Sodium;
        public float VitaminC;
        public float Niacin;
        public float Cholesterol;
        public string Special;
    }

    public FoodItem TempFoodItem;

    public void CreateAllFoods()
    {
        CreateNewFoodItem("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, "");
        CreateNewFoodItem("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, "");
        CreateNewFoodItem("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, .084F, "");
        CreateNewFoodItem("Cheese", 37F, 406F, 24F, .01F, .000F, .027F, .64F, 0F, 0F, .1F, "");
        CreateNewFoodItem("Beef Sausage", 54F, 320F, 12F, .01F, .001F, .013F, .911F, 0F, .003F, .058F, "");
        CreateNewFoodItem("Boiled Eggs", 75F, 155F, 12.5F, .01F, .001F, .010F, .124F, 0F, 0F, .373F, "");
        CreateNewFoodItem("Broccoli", 89F, 34F, 3F, 2.4F, 0F, .021F, .033F, .089F, 0F, 0F, "");
        CreateNewFoodItem("Dry Oats", 8F, 389F, 17F, 10.6F, .005F, .177F, .002F, 0F, .001F, 0F, "");
        CreateNewFoodItem("Ale", 91F, 37F, .2F, 0F, 0F, .007F, .013F, 0F, .001F, 0F, "Inebriation");
        CreateNewFoodItem("Salted Beans", 67F, 127F, 8.67F, 6.4F, .003F, .045F, .238F, .001F, .001F, 0F, "");
        CreateNewFoodItem("Bread", 32F, 278F, 8.4F, 6F, .003F, .081F, .346F, 0F, .004F, 0F, "");
        CreateNewFoodItem("Turnips", 92F, 28F, .9F, 1.8F, 0F, .011F, .067F, .021F, 0F, 0F, "");
        CreateNewFoodItem("Salted Pork", 11F, 748F, 5F, 0F, 0F, .007F, 2.684F, 0F, .002F, .086F, "");
        CreateNewFoodItem("Cabbage", 92F, 25F, 1F, 1.9F, 0F, .012F, .018F, .037F, 0F, 0F, "");
        CreateNewFoodItem("Dried Blueberries", 15F, 317F, 2.5F, 7.5F, .001F, .018F, .003F, .024F, .001F, 0F, "");
        //AddNewFoodToArray(string Name, float Hydration, float Calories, float Protein, float Fiber, float Iron, float Magnesium, float Sodium, float VitaminC, float Niacin, float Cholesterol);
        TempFoodItem = TempFoodItem;
    }

    public void CreateNewFoodItem(string _Name, float _Hydration, float _Calories, float _Protein, float _Fiber, float _Iron, float _Magnesium, float _Sodium, float _VitaminC, float _Niacin, float _Cholesterol, string _Special)
    {
        TempFoodItem = new FoodItem
        {
            Name = _Name,
            Hydration = _Hydration,
            Calories = _Calories,
            Protein = _Protein,
            Fiber = _Fiber,
            Iron = _Iron,
            Magnesium = _Magnesium,
            Sodium = _Sodium,
            VitaminC = _VitaminC,
            Niacin = _Niacin,
            Cholesterol = _Cholesterol,
            Special = _Special
        };
        foodDictionary.Add(_Name, TempFoodItem);
    }
}
</code>```

Body:
Go further

public class NutritionalData
{
    public string Type {get;set;}
    public float Grams {get;set;}
}

public class FoodItem
{
   public string Name {get;set;}
   public List<NutritionalData> NutritionalContent {get;set;}
   public string Description {get;set;}
}


问:
Motivating yourself to actually write the code after you've designed something
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.

答:
Apart from being indeed a matter of motivation, I think that a part of the solution can be found in combining the designing and the coding process. That's how I do it mostly. Basically it comes down to implement the basics of your design when you thought of that, and then move to the next step.

Eg : If I have designed my basic classes, I write them out and run some tests on it. Then I have designed an underlying database, I set it up and test it out. Next I have the methods and functions I need for getting everything in/out of the database, I go on that. The testing is done more easily as I have my basic classes ready already. And when I finally come to design the user interface, I have already a whole set of code ready to play around with.

Now this assumes you also design in blocks that are linked through interfaces. I don't know the expensive word for it, as I'm not a programmer by education, but you know what I mean.

Hope this helps.

ContentLicense: CC BY-SA 2.5


问:
C++ Extensible namespaces - how to force declarations back into global namespace
It is good programming style to include all necessary dependencies in a header that references them. Often this includes declarations that are placed in the STD & global namespaces (like cstdio). However, this creates problems when a second programmer wants to wrap such an include file in a new namespace to encapsulate the first one.

With this scenario in mind, is there a way to force declarations into the global name space? As a conceptual example (this won't actually compile):

```<code>foo.h --> original definition
// force global namespace, this is redundant when foo is in the global space
//   but could be important if foo included into another namespace.
namespace :: {
  #include <cstdio>
}
namespace foo {
  FILE *somefile;
}

bar.h --> New file, by a new programmer, encapsulating foo.
namespace bar {
  # include "foo.h"
  FILE *somefile;  // bar:somefile, as opposed to bar::foo::somefile
}
</code>```

Without the putative namespace ::{} we end up with declarations like foo::FILE, and foo::printf(), when we just want ::FILE and ::printf().

Popular libraries like boost resolve this by defining an explicit hierarchy. That would require that foo know it will be part of bar, and place global namespace includes outside of the local namespace definition.

However, good extensibility requires that we be able to use foo directly, OR wrap foo in a new namespace, without having to change foo or its includes.

Does anyone know how to accomplish this?

答:
The short answer seems to be that namespace hierarchies were designed to be statically defined at design time, and not used in extensive design. That is, not available to wrapped in other namespaces post-design. Thus, they are more a tool for preventing one's own code from polluting the global space, rather than for containing namespace pollution from other people's code.  I believe this limitation is not necessary, but it clarifies my immediate inquiry.

Some additional work yielded a partial solution, but the short answer is that namespaces were not designed to be nested after design. Using them this way, even if possible, is counter to the design intent, and therefore a bad idea. That said, here is a method of achieving it.

I believe most of the issues with linkage could be resolved by two practices:

Making sure that non-inline includes were homed in the global namespace.

Only extending inline / header based namespaces.

The first could be performed now by creating an name_ext.h file for each namespace and including it at global scope. A derived namespace would have its own derived_ext.h that include all dependent name_ext.h, thus employing multiple-include-barriers to insure that global includes were homed in the global namespace. This would preserve binary library linkage. A namespace :: {} extension to home definitions in the global namespace from inside an existing namespace block, would fix this more elegantly.

The second point deals with compile time linkage of .cpp files. I’ve tested this and it works.

The only remaining issue is that of multiply homed classes. Without some substantial preprocessor support for dynamic include-barriers, it would render it impossible to have multi-homed namespaces, which is ultimately a real problem for design orthogonality.

However this would still be limited to namespaces completely contained in include files.

In any case using namespaces this way, even if possible, seems antithetical to current design philosophy.


问:
How should I proceed to make a program that, when given three sides of the triangle in an array, will determine if they can make a valid triangle?
Given three sides of a triangle. I have to determine by writing a program using C language whether I can make a valid triangle or not using these three sides of the triangle. So how should I proceed ?

We all know that a triangle is a geometric shape with three positive sides. However, any given three sides won’t necessarily form a triangle. There is a formula/condition that the biggest side of a triangle is less than the sum of other two sides of the triangle. If this formula/condition is satisfied then we can make a valid triangle using those three sides. Now I have to make a program to find out whether I can make a valid triangle or not using those three positive sides. So, first I have to find out which is the biggest value among the three sides. And for this purpose I have to make a simple program like this…..

```<code>#include <stdio.h>
int main()

{

   int i,side[3],max;

   for( i  = 0; i < 3; i++ )

      scanf("%d",&side[i]);

      max = side[0];

      for( i = 0; i < 3; i++ ){

             if( side[i] > max )

             max = side[i];
    }

    return 0;

    }
</code>```

Now I have get the biggest sides of the triangle through the above program. But now I have got stuck here that next how can I make a program to define whether the biggest side is less than the sum of other two sides of that triangle.

Suppose if we use three different variables rather than the three size array and if we know that the biggest side of triangle is b then simply we will use this condition

```<code>    if ( b < a + c)
        printf("Valid\n");
    else
        printf("In-valid\n");
</code>```

but as I used an array here rather than three different variables, I can’t write this code simply to determine whether the triangle will be valid or not. Using an array, it is simply easy to find out the biggest side of the triangle but using array I can’t check the condition of forming triangle here.

So in this circumstance what should I do?

答: Rather than saving max as the VALUE of the largest side, try saving max as the index of the value instead.  Then since you know which element in the array contains the max value, just add the other 2 elements and compare to the value pointed to by max.</p>


问:
How do you look for programmers when your project's not in a particularly popular language?
So, we've got a product, written in Perl. Mind you, it's good Perl, pretty well object-oriented, with a strong functional-programming influence, extensive test suites, and it's an agile environment doing Extreme Programming with elements of Scrum.

We also have about 4 open headcount that we're trying to fill sooner rather than later, and we've historically had trouble filling even just one or two. I've been taking a look at the sort of candidates that our existing postings seem to be attracting, and they're not particularly impressive. Most of them have a background in QA automation or something similar.

We know that we can take good OO software engineers who know Python or Ruby or even just C++/Java and bring them up to speed quickly enough. We're pretty good at being able to pitch the actual job itself to qualified candidates if we have their ear. What we're not good at, it seems, is attracting these people to our postings in the first place.

What sort of things can we do to market ourselves to these engineers?

What sort of things should we be careful to avoid in job postings and the like?

(The posting is omitted since I don't want to get in any trouble by doing an end-run around the job-board. Also, our current in-house recruiter isn't helping much.... rumors are his days are numbered and I'm not at all surprised...)

答:
Are you restricted by your geographic location? Are you only trying to attract people from within a certain area. If you have a specific skillset requirement, you may need to cast a broad net. You don't specify how you're seeking people.

Do you allow work-from-home? If not, why not. What is it about your development that can't be done remotely. Maybe you could have someone on-site for a few weeks and then let them go home. That would expand considerably the people that might be interested in working for you.

Do your postings reflect that you value these skills. That you're pro-active in supporting education and knowledge. That you encourage activity on forums, user-groups, etc. That your enterprise understands and promotes the value of expertise?

And of course, what are the rates you're paying. Too often I see that companies don't adequately value a specialist skill-set. Rather than valuing what cost-benefit the company may attract from that resource(person) they just think of what pay scale a programmer should fall into. But if your company can earn big $ from what that person produces, review the pay scale! (If I make or save your company $500K per year, what percentage of that am I worth?).

Basically, if you're not attracting the right people, you need to look inward first.


问:
Python OO problem
I started learning Python yesterday and I ran into a problem. I like to hear some thoughts on it.

As an exercise, I decided to build a chatserver. As part of the exercise, I wanted to write some inheritance code.

```<code>Class A
  def foo
    print "foo"

Class B(A)
  def bar
    print "bar"

c = B()
c.foo()
>>> prints: foo
</code>```

okay, to me that seems like very normal basic inheritance (please let me know if you disagree). So to get back to my chatserver, I thought it would be nice to extend the socket and make it into a chat socket. The first thing I wanted to do is add an attribute called nickname (important in a chat).
Oh, and I thought about using select as a threading solution because it seemed to come highly recommended, so you need an array of sockets (I also like to hear your thoughts on this).
Now, the problem you get is, that socket, instantiates sockets, so

```<code>s = socket.socket(family, type,..)
</code>```

in stead of

```<code>s = Socket()
</code>```

so what I wanted todo is

```<code>class ChatSocket(Socket)
  def getNickname()
    return "bob" # obviously an example for simplicity

s = ChatSocket()
</code>```

First question:
Why does it work this way and doesn't it have a 'normal' instantiation?

Second question:
What is in your opinion an elegant solution to this challenge?

I hope this makes sense...
Any thoughts are very welcome

答:
```<code>s = socket.socket(family, type,..)
</code>```

in stead of

```<code>s = Socket()
</code>```

Why does it work this way and doesn't it have a 'normal' instantiation?

But that is normal initalization! socket is a module (or namespace), and socket.socket is the socket class in the socket namespace, and socket.socket(family, type) invokes that constructor. This might be clearer if you import that module under a custom name:

```<code>import socket as socketmodule
# then:
s = socketmodule.socket(...)
</code>```

Or you could alias the name of the class:

```<code>Socket = socket.socket
s = Socket(...)
</code>```

In Python, modules and classes are ordinary values that are passed around at runtime, so we can use ordinary variables to name them.

You can subclass the built-in socket to provide custom behaviour. For example:

```<code>class ChatSocket(socket.SocketType):
  def __init__(self):
    super(socket.SocketType, self).__init__(family, type) # assuming Python 2.x
    other_initalization()

  def nickname(self):
    return "bob"
</code>```

(The names socket.socket and socket.SocketType are the same class.)

However, subclassing a class you have no control over and that is not intended for subclassing might not be a good idea. Instead, stuff the socket into a member variable and wrap any methods you want to expose:

```<code>class ChatSocket(object):
  def __init__(self):
    self.socket = socket.socket()

  def nickname(self):
    return "bob"

  def accept(self):
    return self.socket.accept()

  ...
</code>```

This lets you control more precisely what interface your class offers.

Title: Python OO problem

Body:
s = socket.socket(family, type,..)

in stead of

s = Socket()

Why does it work this way and doesn't it have a 'normal' instantiation?

But that is normal initalization! socket is a module (or namespace), and socket.socket is the socket class in the socket namespace, and socket.socket(family, type) invokes that constructor. This might be clearer if you import that module under a custom name:

import socket as socketmodule
# then:
s = socketmodule.socket(...)

Or you could alias the name of the class:

Socket = socket.socket
s = Socket(...)

In Python, modules and classes are ordinary values that are passed around at runtime, so we can use ordinary variables to name them.

You can subclass the built-in socket to provide custom behaviour. For example:

class ChatSocket(socket.SocketType):
  def __init__(self):
    super(socket.SocketType, self).__init__(family, type) # assuming Python 2.x
    other_initalization()

  def nickname(self):
    return "bob"

(The names socket.socket and socket.SocketType are the same class.)

However, subclassing a class you have no control over and that is not intended for subclassing might not be a good idea. Instead, stuff the socket into a member variable and wrap any methods you want to expose:

class ChatSocket(object):
  def __init__(self):
    self.socket = socket.socket()

  def nickname(self):
    return "bob"

  def accept(self):
    return self.socket.accept()

  ...

This lets you control more precisely what interface your class offers.


答:
While it's true that the triangle inequality is c < a + b, this is equivalent to 2c < a + b + c, which is a lot easier to do. You can calculate the running total without knowing the max, and by the time you get to the end you will already know the max. See the below code:

```<code>#include <stdio.h>
int main() {
  int i, side[3], max = -1, total = 0;

  for(i=0; i < 3; i++) {
    scanf("%d",&side[i]);
    max = side[i] > max ? side[i] : max;
    total += side[i];
  }

  if (2 * max < total) {
    printf("Valid\n");
  } else {
    printf("In-valid\n");
  }

  return 0;
}
</code>```

Ideone link

As an aside, I recommend using curly braces for all your code blocks, as it makes the code easier to follow, and using proper indentation. ? : is the ternary operator, which is a way to do quick if statements in line.

Title: How should I proceed to make a program that, when given three sides of the triangle in an array, will determine if they can make a valid triangle?

Body:
Given three sides of a triangle. I have to determine by writing a program using C language whether I can make a valid triangle or not using these three sides of the triangle. So how should I proceed ?

We all know that a triangle is a geometric shape with three positive sides. However, any given three sides won’t necessarily form a triangle. There is a formula/condition that the biggest side of a triangle is less than the sum of other two sides of the triangle. If this formula/condition is satisfied then we can make a valid triangle using those three sides. Now I have to make a program to find out whether I can make a valid triangle or not using those three positive sides. So, first I have to find out which is the biggest value among the three sides. And for this purpose I have to make a simple program like this…..

```<code>#include <stdio.h>
int main()

{

   int i,side[3],max;

   for( i  = 0; i < 3; i++ )

      scanf("%d",&side[i]);

      max = side[0];

      for( i = 0; i < 3; i++ ){

             if( side[i] > max )

             max = side[i];
    }

    return 0;

    }
</code>```

Now I have get the biggest sides of the triangle through the above program. But now I have got stuck here that next how can I make a program to define whether the biggest side is less than the sum of other two sides of that triangle.

Suppose if we use three different variables rather than the three size array and if we know that the biggest side of triangle is b then simply we will use this condition

```<code>    if ( b < a + c)
        printf("Valid\n");
    else
        printf("In-valid\n");
</code>```

but as I used an array here rather than three different variables, I can’t write this code simply to determine whether the triangle will be valid or not. Using an array, it is simply easy to find out the biggest side of the triangle but using array I can’t check the condition of forming triangle here.

So in this circumstance what should I do?

Body:
While it's true that the triangle inequality is c < a + b, this is equivalent to 2c < a + b + c, which is a lot easier to do. You can calculate the running total without knowing the max, and by the time you get to the end you will already know the max. See the below code:

#include <stdio.h>
int main() {
  int i, side[3], max = -1, total = 0;

  for(i=0; i < 3; i++) {
    scanf("%d",&side[i]);
    max = side[i] > max ? side[i] : max;
    total += side[i];
  }

  if (2 * max < total) {
    printf("Valid\n");
  } else {
    printf("In-valid\n");
  }

  return 0;
}

Ideone link

As an aside, I recommend using curly braces for all your code blocks, as it makes the code easier to follow, and using proper indentation. ? : is the ternary operator, which is a way to do quick if statements in line.


问:
Why do XSLT editors insert tab or space characters into XSLT to format it?
All XSLT editors I've tried till now add tab or space characters to the XSLT to indent it for formatting. This is done even in places within the XSLT where these characters are significant to the XSLT processor.

XSLT modified for formatting in this way can produce output very different to that of the original XSLT if it had no formatting. To prevent this, xsl:text elements or other XSLT must be added to a sequence constructor to help separate formatting from content, this additional XSLT impacts on maintainability. Formatting characters also adversely impact on general usability of the tool in a number of ways (this is why word-processors don't use them I guess) and add to the size of the file.

As part of a larger project I've had to develop a light-weight XSLT editor, it's designed to format XSLT properly, but without tab or space characters, just a dynamic left-margin for each new line. The XSLT therefore doesn't need additional elements to separate formatting tab or space characters from content. The problem with this is that if XSLT from this editor is opened in other XSLT editors, characters will be added for formatting reasons and the XSLT may therefore no longer behave as intended.

Why then do existing XSLT editors use tabs or spaces for formatting in the first place?

I feel there must be valid reasons, perhaps historical, perhaps practical. An answer will help me understand whether I need to put compatibility options in place in my XSLT editor somehow, whether I should simply revert to using tabs or spaces for both XSLT content and formatting (though this seems like a backwards step to me), or even whether enough XSLT users might be able to persuade their tools vendors to include alternative formatting methods to tabs or spaces.

Note: I provided an XSLT sample demonstrating formatting differences in this answer to the question: Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?

答:
Why then do existing XSLT editors use tabs or spaces for formatting in the first place?

I would imagine because

This feature was already default in HTML, XML, and similar editors on which the XSLT editing environment is based

Spaces/Tabs improve legibility of the file, and adding actual spaces is easier than adding virtual spaces

Users may have opinions about how much whitespace to put where, and these opinions are sometimes informed.

Line breaks mean line-based error messages are meaningful

In most contexts, extra whitespace in XSLT has no effect on the resulting document

In the contexts where it does have an effect on the resulting document, in at least some cases the semantics of that document won't change.

The only real problem for XSLT is whitespace in mixed content. In this case, as you note, you can use xsl:text. Yes, it adds overhead, and it's annoying at times.

But in several years of working with XSLT in practice (including using it to do lots of fiddly punctuation-related tasks), my impression is that, on balance, it's not a bad thing. In fact, I would generally discourage entry of raw text in any context other than xsl:text because of the danger of the significant whitespace issue.

Insertion of plain static text in XSLT is generally something you want to do only sparingly and after careful consideration. Most of XSLT's power and expressiveness is in its ability to reshape data, rather than its text-processing capabilities. Deciding to do add whole text nodes is worthy of an extra tag to flag up 'this is deliberately doing something slightly unusual'.

Because of this and because of the nature of markup and text in XML and XSLT, text processing tasks need to be done carefully. Putting each text node in its own element on its own line, on a par with other nodes and instructions helps in that conscious process.

Finally, it's worth bearing in mind that XSLT is not terse to begin with. An extra bit of overhead is therefore not a big deal. Storage on this level is cheap, and even if used frequently, additional transfer costs will be negligible once gzipping is taken into account.

I would encourage you to think again about the "a dynamic left-margin for each new line" solution, and suggest that you instead code something which gracefully handles mixed content by automatically wrapping the necessary elements in xsl:text (which you could hide). This would make the XSLT you generate more resilient to other tools.


问:
Designing around shallow constness with inheritance

Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.

答:
Create an abstract class ReadableImage. Derive both MutableImage and ImmutableImage (and also ImageSlice) from this class. Then the is-a relations hold. Don't take ImmutableImage parameters in functions unless the function actually expects the image to really be immutable, for example because it expects it to not be modified by another thread.

The annoying part of this is slicing, but that's a problem that you always face with class hierarchies representing data in C++.


问:
Observer for two independent events in the observable class
Observer pattern aim: the observer class responds to the changes of the observable class state.

Problem. There are different processes inside observable class that should be observed. Those events are independent and the state is not single value but rather itself is a set of different processes.

That might be bad design, the observable class is too big and should be split into smaller ones. But what if we cannot refactor that class and we have to observe it.

Question. Should we have single Observer for all state changes (processes, events). Or should we create one Observer for each state change (process, event).

Or maybe applying observer is the bad idea at all and another design pattern should bu used.

Example

The example might look as artificial for the observer pattern but should be viewed as minimal example.

Consider search form where user can look for:

author

title

both author and title

There is the Reader class responsible for getting the parameters.

There is additional task: store words that the users are looking for in the file (simplified logger). We want to store author values in one file and title values in the another.
We do not want add any responsibilities for the Reader class nor extend it. We want observe its inner state.

One state change (event) happens when the author parameter is read from the form.
Second state change (event) happens when the title parameter is read from the form.
Those events are independent. We are not interested in whole Reader state (only author, only title, title and author). We are interested only in states of parameter readers (author read or not) (title read or not).

One observer for all events

When observer is notified, it does not know which event happened. The additional property whichState is introduced. The observer must check its value (SEARCH_BY_AUTHOR or SEARCH_BY_TITLE)  in the update() method.

Code:

<?php
class Reader implements \SplSubject
{
    private $observers;
    public $author = null;
    public $title = null;
    // additional property to determine which state is observed
    public $whichState = null;
    // states
    const SEARCH_BY_AUTHOR = 'author';
    const SEARCH_BY_TITLE  = 'title';

    public function __construct()
    {
        $this->observers  = new \SplObjectStorage();
    }

    public function attach(\SplObserver $observer)
    {
        $this->observers->attach($observer);
    }

    public function detach(\SplObserver $observer)
    {
        $this->observers->detach($observer);
    }

    public function notify()
    {
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }

    /* simulates reading from form */
    public function readParams(array $params)
    {
        if (array_key_exists('author', $params) === true) {
            $this->author     = $params['author'];
            $this->whichState = Reader::SEARCH_BY_AUTHOR;
            $this->notify();
        }
        if (array_key_exists('title', $params) === true) {
            $this->title      = $params['title'];
            $this->whichState = Reader::SEARCH_BY_TITLE;
            $this->notify();
        }
    }
}

class BothParamsObserver implements \SplObserver
{
    public function update(\SplSubject $subject)
    {
        if ($subject->whichState === Reader::SEARCH_BY_AUTHOR) {
            $author = $subject->author . "\r\n";
            file_put_contents("authors.txt", $author, FILE_APPEND);
        }
        elseif ($subject->whichState === Reader::SEARCH_BY_TITLE) {
            $title  = $subject->title  . "\r\n";
            file_put_contents("titles.txt", $title, FILE_APPEND);
        }
    }
}

$reader = new Reader();
$bothParamsObserver = new BothParamsObserver();
$reader->attach($bothParamsObserver);

file_put_contents("authors.txt", "");
file_put_contents("titles.txt", "");
// simulate receiving forms
$reader->readParams(array("title" => "PHP"));
$reader->readParams(array("author" => "Zandstra"));
$reader->readParams(array("title" => "PHP", "author" => "Zandstra"));
?>
```

<h2>Two observers, each for one event</h2>

<p>The observers are duplicated inside the observable class. There is one collections <code>authorObservers</code> and the other <code>titleObservers</code>. There are methods <code>attachAuthorObserver()</code>, <code>detachAuthorObserver()</code>, <code>notifyAuthorObservers()</code> and there are methods <code>attachTitleObserver()</code>, <code>detachTitleObserver()</code>, <code>notifyTitlerObservers()</code>.</p>

<p><img src="https://i.stack.imgur.com/D8Bxh.png" alt="enter image description here"></p>

<p>Code</p>

<pre class="lang-php prettyprint-override"><code><?php
class Reader
{
    private $authorObservers;
    private $titleObservers;
    public $author = null;
    public $title = null;

    public function __construct()
    {
        $this->authorObservers = new \SplObjectStorage();
        $this->titleObservers  = new \SplObjectStorage();
    }

    public function attachAuthorObserver($observer)
    {
        $this->authorObservers->attach($observer);
    }

    public function attachTitleObserver($observer)
    {
        $this->titleObservers->attach($observer);
    }

    public function detachAuthorObserver($observer)
    {
        $this->authorObservers->detach($observer);
    }

    public function detachTitleObserver($observer)
    {
        $this->titleObservers->detach($observer);
    }

    public function notifyAuthorObservers()
    {
        foreach ($this->authorObservers as $observer) {
            $observer->update($this);
        }
    }

    public function notifyTitleObservers()
    {
        foreach ($this->titleObservers as $observer) {
            $observer->update($this);
        }
    }

    /* simulates reading from form */
    public function readParams(array $params)
    {
        if (array_key_exists('author', $params) === true) {
            $this->author     = $params['author'];
            $this->notifyAuthorObservers();
        }
        if (array_key_exists('title', $params) === true) {
            $this->title      = $params['title'];
            $this->notifyTitleObservers();
        }
    }
}

class AuthorObserver
{
    public function update($subject)
    {
        $author = $subject->author . "\r\n";
        file_put_contents("authors.txt", $author, FILE_APPEND);
    }
}

class TitleObserver
{
    public function update($subject)
    {
        $title  = $subject->title  . "\r\n";
        file_put_contents("titles.txt", $title, FILE_APPEND);
    }
}

$reader = new Reader();
$authorObserver = new AuthorObserver();
$titleObserver = new TitleObserver();
$reader->attachAuthorObserver($authorObserver);
$reader->attachTitleObserver($titleObserver);

file_put_contents("authors.txt", "");
file_put_contents("titles.txt", "");
// simulate receiving forms
$reader->readParams(array("title" => "PHP"));
$reader->readParams(array("author" => "Zandstra"));
$reader->readParams(array("title" => "PHP", "author" => "Zandstra"));
</code>```

Update: solution

Specific solution based on Robert Harvey's answer.

Code

<?php
class Reader implements \SplSubject
{
    private $observers;
    public $author = null;
    public $title = null;
    // additional property to determine which state is observed
    public $whichState = null;
    // states
    const SEARCH_BY_AUTHOR = 'author';
    const SEARCH_BY_TITLE  = 'title';

    public function __construct()
    {
        $this->observers  = new \SplObjectStorage();
    }

    public function attach(\SplObserver $observer)
    {
        $this->observers->attach($observer);
    }

    public function detach(\SplObserver $observer)
    {
        $this->observers->detach($observer);
    }

    public function notify()
    {
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }

    /* simulates reading from form */
    public function readParams(array $params)
    {
        if (array_key_exists('author', $params) === true) {
            $this->author     = $params['author'];
            $this->whichState = Reader::SEARCH_BY_AUTHOR;
            $this->notify();
        }
        if (array_key_exists('title', $params) === true) {
            $this->title      = $params['title'];
            $this->whichState = Reader::SEARCH_BY_TITLE;
            $this->notify();
        }
    }
}

class AuthorObserver implements \SplObserver
{
    public function update(\SplSubject $subject)
    {
        if ($subject->whichState === Reader::SEARCH_BY_AUTHOR) {
            $author = $subject->author . "\r\n";
            file_put_contents("authors.txt", $author, FILE_APPEND);
        }
    }
}

class TitleObserver implements \SplObserver
{
    public function update(\SplSubject $subject)
    {
        if ($subject->whichState === Reader::SEARCH_BY_TITLE) {
            $title  = $subject->title  . "\r\n";
            file_put_contents("titles.txt", $title, FILE_APPEND);
        }
    }
}

$reader = new Reader();
$authorObserver = new AuthorObserver();
$titleObserver = new TitleObserver();
$reader->attach($authorObserver);
$reader->attach($titleObserver);

file_put_contents("authors.txt", "");
file_put_contents("titles.txt", "");
// simulate receiving forms
$reader->readParams(array("title" => "PHP"));
$reader->readParams(array("author" => "Zandstra"));
$reader->readParams(array("title" => "PHP", "author" => "Zandstra"));
?>
```

答:
It should be two observers.

Your Reader object should not have observer-specific attach and detach methods.  Rather, it should have two methods for registering and de-registering concrete observer objects in a single observer collection.

Wikipedia

You can still use Reader:WhichState in your concrete observers to determine whether or not each concrete observer should take any action.


问:
Role of an architect in SAP ABAP or SAP BI projects
Given that SAP modules are architected and managed by SAP itself.

However, small changes are possible at the customer's end.

How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do?

答:
In my experience, there is a lot of flexibility at the clients end. The software needs to be used in different new ways for new business cases. Someone has to design these usages. That's what an architect at the client's end is for.
Is that answering your question?</p>


答:
Conceptually, there should be no particular difficulty with designing C source files so they they can also be compiled as-is with C++.  There can indeed be some significant advantages to doing this.  For example, when writing code for an embedded system it is sometimes helpful to be able to test the code on a hosted PC environment.  If the code compiles cleanly as C++, it's possible to have a statement like "MOTOR_ENABLE = 1;" write to a volatile I/O bit on the embedded system (compiled as C), but trigger emulation logic on the PC (compiling as C++).  It would also probably be possible to design a C++ type on the PC which would behave the way a uint16_t behaves on smaller embedded systems (so that e.g. given u16 x=65533;, a compiler would have to regard the value of x*x as nine, rather than having free reign to do anything it wants), though as yet none of my emulators have included that [in part because the C++ compilers I've used haven't done anything wacky in such cases].

Unfortunately, C programmers and C++ programmers have sufficient antipathy toward each other that the languages have, over the years, evolved in compatible ways.  While C89 attempted to adapt some of the more useful features of C++ (such as function prototypes) an attitude seems to have emerged that programmers who want any of the features of C++ should use C++, ignoring the fact that there are many situations where it would be helpful to be able to use some of the features of C++ (e.g. the ability to overload functions with static or static inline linkage without having to accept the costs associated with other features that one doesn't need (e.g. the name mangling associated with exporting overloaded functions).

While the intersection of C89 and C++98 is a workable language, the usable superset of later versions of C with later versions of C++ has probably shrunk rather than grown (thanks to things like the Strict Aliasing Rule) and trends favor an ever-increasing fissure.

Title: Should I stop using the term C/C++?

Body:
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

Should I stop using the term C/C++?

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these questions so I'm very interested to get good answers especially for the points that have to do with the C++ tendency in the near future.


问:
Threads Inside Full Duplex Device Library
This is the second project I'm working on which will use a design that I'm not 100% confident about.  I'd like some feedback, maybe recommendations for a better design, or verification that this would be acceptable by more proficient programmers:

I have a device that I need to interface with.  Be it via TCP, UART, UDP, or whatever. I need to send this device data/control, and receive data/control information from this device, but it's not exactly a request/response sort of situation.  The device can send data at random times without user stimulus.  For instance, the newest device is a full-duplex radio.  When the radio correctly demodulates and decodes digital packets, he will send the voice data via UDP to my library.  It doesn't wait for a user for input.  When you want to send stuff out over the air, I send control information, and then data for the radio to modulate and push over the air.

Packets that go between my library and the device are framed: ie, each packet is prepended a header (and other metadata to identify the type of packet) and appended a CRC and footer so I know a) the start of a packet in case garbage is somehow introduced over the stream, and b) the data is correct (by verifying the footer, and the correct CRC).

Okay, so I'm designing a library that will need to be handed to a different developer for application development.  So all the internals are abstracted away from him.  For ease in this example, I want this library to have 4 calls: send_data, receive_data, send_voice, receive_voice.  The different packet types (voice and data) are sent over one port.  The library can frame and parse the appropriate packets (for sending and receiving, respectively), and so can the device.

For sending data to the device:

This is easy.

The application developer calls either send_data or send_voice.  I take relevant voice or data, frame it accordingly, and send it to the device.  The device parses the data, and sends it on its way.  The calls are thread safe, so the developer can't call a UDP send asynchronously.

For receiving data from the device:

This is where I'm not 100% confident in the design.

I start a receive (RX) thread in my library.  When I get a packet (either voice or data), I de-frame the packet, and put either the voice or data on a respective queue (a voice queue and a data queue).

When the application developer wants voice, he calls receive_voice and it will return a pop from the voice queue.  When the application developer wants data, he calls receive_data and it will return a pop from the data queue.
Obviously I'm careful the queues can't grow to infinity, and when a queue is MAX_QUEUE_LEN, I pop a voice/data packet off the queue and discard it before putting a new one on, and set a 'overrun' flag.  This flag can be set/read with set_X_overrun, or get_X_overrun, where X is voice or data depending on the queue.

I actually like the design.  However, what do other people think?  I'm not sure what people think about putting a running thread inside of a library?  I guess the other option is just to have read_data and read_voice calls that will block until a packet is found that matches what they want (voice or data).  This eliminates the need for a running thread, but then the opposite packet is essentially disregarded while we wait for the one of choice.  Or is there another design I'm not even thinking about?

Sorry about the long-winded and probably unclear design question.  Now that I feel like more of a confident programmer using the semantics/syntax of languages themselves, I've been getting much more interested in the design of programs rather than the nitty-gritty of the lower level calls.  I'm striving for the best/coolest design possible rather than something that 'just works.'

Bonus points if there's some sort of open source software out there that I can look into and improve my design.

Image of design:

]

Pseudo code:

public void send_data(buf) {
    frame_data_packet(buf);
    udp_send(buf);
}

public void send_voice(buf) {
    frame_voice_packet(buf);
    udp_send_(buf);
}

public void receive_data(buf) {
    buf = data_queue.pop();
}

public void receive_voice(buf) {
    buf = voice_queue.pop();
}

/* RX Thread */
public void run_rx()
{
    while (run_rx_f) {
        type = deframe_data(data);
        switch (type) {
            case VOICE:
                voice_queue.add(data);
                break;
            case DATA:
                data_queue.add(data);
                break;
        }
    }
}
```

答:
Addressing a possible improvement: Could improve your design by having a generic send() and receive() accepting an Abstract buffer class and two classes of Voice and Data buffers that extend it.

This makes your internal code easier to handle and can enhance modularity and extensibility. ie) allows ease for you to possibly improve support different types of send and receive methods without a method explosion from your library. Say you want to add capability to specially handle images.

The VoiceBuffer and DataBuffer classes could even be abstract, forcing whoever is going to implement your library to address how the buffer of data is constructed.


答:
TL; DR

(Personal, unproven idea)

"This cptr is const, that mptr is not

Almost-proven idea, on top of OpenCV's Mat_<T> design

Bake const-ness into the template parameter T, and

Make sure all holes are plugged, by making some changes to OpenCV.

This is a tough one, and one that even well-known imaging libraries such as OpenCV do not find a perfect solution. Instead most people would live with pragmatism, i.e. be satisfied with whatever they have got.

Here is my unproven idea:

In each Image class (and Buffer class as well), maintain two raw pointer fields:

One is a non-const void (or uchar) pointer.

One is a const void (or uchar) pointer. (Meaning that it does not allow one to modify the data being pointed to, via this pointer.)

In Image instances that need to "enforce const-ness", even if someone has managed to obtain a non-const-qualified reference to that Image, the non-const pointer is intentionally set to nullptr.

Before any pixel modifications, someone will have to validate the pointer before proceeding. Typically, if one intends to modify a whole bunch of pixels, one only needs to validate the pointer once, so with proper design this should not become a performance overhead.

All modifications will be done via the non-const pointer, and all read-only operations will be done via the const pointer.

For mutable images (or, images that allow modifications), the two pointers will always have the same value.

This is just a wild, unproven idea. Feel free to explore and critique. That said, my idea is brewed from long time use of OpenCV and low-level image processing implementations.

As a bonus, if you are already familiar with OpenCV, you can try the following two declarations:

    const auto sz = cv::Size(3, 3);
    const uchar fillval = 0U;
    cv::Mat_<uchar> matMutable1B(sz, fillval);
    cv::Mat_<const uchar> matImmutable1B(sz, fillval);

Notice that the first one allows modifications via the usual OpenCV style, e.g. mat.at(row, col) = fillval;, mat(row, col) = fillval;, mat.ptr(row)[col] = fillval;, whereas the second one doesn't allow.

This is due to the template parameter <T> being const-qualified by the second declaration.

However, as of currently, this is not foolproof, because someone who obtain the pointer via mat.data will get a uchar*, regardless of the const-qualification of template parameter <T>.

One very important distinction about immutability / object state access control versus C++ style notational const-qualification

C++ const-qualification affects code which "come by / obtain" a reference to a certain class. Thus, it passes along const-qualification by something like a chain-of-custody of types. The Image itself cannot find out whether someone owning a reference to it and making a call to it is const-qualified or not. Instead, C++ enforces this when type-checking the caller's code, and blocks the caller's attempt. The Image class never knows.

My idea of using two pointers (const / non-const) and setting the non-const to nullptr is an attempt to solve this issue at runtime. Thus, someone who obtains an Image that is not const-qualified, but its non-const data pointer is nullptr, will face runtime consequences.

Ultimately, if this is too difficult to discuss, maybe just spend some time with OpenCV, and try both const-qualify the matrix itself as well as the template parameter, to see which technique satisfies the most of your requirements.

Another lesson learned from OpenCV is that you must implement your own reference-counting mechanism in the image class. Failure to do so makes the library user's code very brittle.

Title: Designing around shallow constness with inheritance

Body:
Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.


问:
Should exceptions be raised higher up or lower down or both?
When calling some function in a Python application, the function often calls functions deeper down which again call functions deeper down, etc. It is easy to unknowlingly pass a bad value to the top-level function which will cause a failure further down. Naturally, the parameters should be checked and exceptions raised with helpful error messages. But where should this ideally be done, and why?

As high up as possible (error messages are probably easier to understand since they're closer to the user)

As low down as possible (exception messages are closer to where the errors would actually occur, and the checks may be simpler since they probably don't depend on some obscure combination of input values, but the messages and variable names might be so far removed from the user that the only way of knowing what actually must be changed in the top-level call is to inspect the source from top to bottom)

Both

答:
Throw an exception the moment that you know your code isn't going to be able to recover from an error condition on its own (i.e. without user intervention).

Example:  Your code determines that a supplied path to a disk file does not exist, and the code cannot proceed without a good path.  Throw at that moment, wherever it happens in your code.

Always include in the error message enough information to diagnose the problem. Preserve the call stack; you'll need that to get back to the place in the code where the exception was thrown.  The call stack will tell you not only where the throw occurred, but every function or method call that took place up to the moment of the throw.

The whole point of exception handling is to provide the ability to throw an exception anywhere an unrecoverable error condition happens.


问:
Should I use the new C++11 'auto' feature, especially in loops?
What are the pros/cons to using the auto keyword, especially in for loops?

```<code>for(std::vector<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->something();
}

for(std::map<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->second->something();
}

for(auto it = x.begin(); it != x.end(); it++ )
{
   it->??
}
</code>```

Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use first or second or just directly access properties of the object, no?

This reminds me of the C# debate on whether to use the keyword var.  The impression I'm getting so far is that in the C++ world people are ready to adopt the auto keyword with less of a fight than var in the C# world.   For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.

答:
Yes, you should use auto as a default rule. It has raw advantages over explicitly specifying the type:

It does not make you type things the compiler is already aware of.

It makes the type of variables "follow along" any change in return value types.

Doing so, it prevents silent introduction of implicit conversions  and slicing in local variable initialization.

It removes the need of some explicit type calculations in templates.

It removes the need of naming return types with long names. (the ones you copy-paste from compiler diagnostics)

This is where you have a choice. There are also cases where you don't have a choice:

It permits declaration of variables of unutterable types, like the type of a lambda.

Provided that you know exactly what auto does, it has no disadvantages.


问:
UUID vs Integer
For a database. Should I use an UUID or an integer for the primary key?

I will never exceed 2^32 in amount of rows, so an integer should be more than plenty.

I would prefer to use an integer, as I find it easier to work with, especially when using different languages.

Question: What is the advantage of UUIDs over integers?

答:
The intent of UUIDs is to enable distributed systems to uniquely
  identify information without significant central coordination. (Wikipedia)

UUIDs are merely integers that are picked at random by nodes that cannot necessarily communicate with each other, so they are only very, very likely to be unique rather than guaranteed. If you're programming a NON-distributed system, there is no advantage.

Title: UUID vs Integer


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
It all depends on you as long as you are not working on a project where some coding constraints or some standards have been set by the project manager that all the programmers who are working on that project have to follow while coding.

I personally would prefer the 1st method.

Also I didn't get what you wanna show by the 3rd method?

Isn't that a wrong way? For example consider a situation as..

```<code>if (you.hasAnswer())
  you.postAnswer();
else
  you.doSomething();
</code>```

Now what if someone wants to add some more statements in the if block?

In that case if you use the 3rd method the compiler will throw the syntax error.

```<code>if (you.hasAnswer())
   you.postAnswer1();
   you.postAnswer2();
else
   you.doSomething();
</code>```

Body:
It all depends on you as long as you are not working on a project where some coding constraints or some standards have been set by the project manager that all the programmers who are working on that project have to follow while coding.

I personally would prefer the 1st method.

Also I didn't get what you wanna show by the 3rd method?

Isn't that a wrong way? For example consider a situation as..

if (you.hasAnswer())
  you.postAnswer();
else
  you.doSomething();

Now what if someone wants to add some more statements in the if block?

In that case if you use the 3rd method the compiler will throw the syntax error.

if (you.hasAnswer())
   you.postAnswer1();
   you.postAnswer2();
else
   you.doSomething();


答:
The answer is "3. Both." Every layer offers a specific interface, and this interface has specific constraints. These constraints should always be enforced by means of validation. One layer is not supposed to do another layer's validation, nor rely on another layer to do its validation for it.  If you move a layer into a different system, it should still be able to function.

All unexpected exceptions (exceptions about things that normally should not happen) indicate a bug in the code that threw the exception, except "InvalidArgumentException", which indicates a bug in the code that called the code that threw the exception.

So, if layer A invokes layer B, and layer A contains a bug causing it to pass wrong information to layer B, but layer B does not do its own validation, then layer B will throw some "FailedToDoWhatYouAskedMeToDo" exception, at which point you will naturally start looking for the bug in layer B.  If layer B does its own validation, then layer B will throw an "InvalidArgumentException" instead, thus pointing you to look for the bug in layer A.

So, if you do not have every layer do its own validation, then you will be constantly confused about where a bug is.  You will often have one layer which is throwing an exception for a bug which exists in another layer, which is another way of saying that you may have a bug somewhere and expect a different layer to find it.  This is chaos, and to be avoided at all costs.

There is a subtle point which is perhaps worth mentioning in the case of Python, because as far as I know, Python is a bit inconvenienced with respect to distinguishing public vs. private stuff.  Normally, you may avoid duplication of validation within a specific layer, by having only public functions do validation. In other words, private functions of a layer do not need to be repeating validation that has already been done by public functions. But if all functions are public, then all of them need to do validation.

Title: Should exceptions be raised higher up or lower down or both?

Body:
When calling some function in a Python application, the function often calls functions deeper down which again call functions deeper down, etc. It is easy to unknowlingly pass a bad value to the top-level function which will cause a failure further down. Naturally, the parameters should be checked and exceptions raised with helpful error messages. But where should this ideally be done, and why?

As high up as possible (error messages are probably easier to understand since they're closer to the user)

As low down as possible (exception messages are closer to where the errors would actually occur, and the checks may be simpler since they probably don't depend on some obscure combination of input values, but the messages and variable names might be so far removed from the user that the only way of knowing what actually must be changed in the top-level call is to inspect the source from top to bottom)

Both


问:
Should it use counter, or flag inside objects, to indicate progress?
For example, I have a game, it has 5 enemies which attack once sequentially at each round:

```<code>class Enemy{
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

I want something to indicate which enemy has attacked and which has not, now I have 2 solutions:

1.add a counter "enemyIndex" to indicate which enemy is attacking, after each enemy attacked, the "enemyIndex" counter automatically +1:

```<code>class Enemy{
};

class Game{
public:
    int enemyIndex;
    Enemy enemys[5];
};
</code>```

2.each Enemy object adds a flag "isAttacked", after the enemy attacked, its  "isAttacked" flag marked from false to true:

```<code>class Enemy{
public:
    bool isAttacked;
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

which one is more reasonable in terms of design pattern?

答:
Only enemyIndex fulfills the "which attack once sequentially" criteria.

However, presumably you'll want to vary the attack pattern at some stage. To make this easy to do, I would add unique Ids to each enemy and pass a list of them to an AI class which would contain the attack order logic, creating an order from the Ids, keeping track of who has attacked and causing each to attack in turn.

Try to avoid baking the logic into your data structures.