问:
Planning poker with visually impaired colleague
At the office we just got a new colleague who is visually impaired.

I'm in charge of organizing the planning poker sessions and the new colleague must participate as a member of the team. We have these nice sets of poker cards with planning poker numbers on them, but that doesn't help of course for our new colleague.

Until now we fixed this problem by just naming the estimates, letting the new colleague say their estimate right after the rest had put down their card, then the rest flips their card and I name the estimates in a row.

My question(s): Is there any one who has experience with this kind of situation and have a better solution? Is there such a thing as Braille poker cards?

The current solution does work, but I think this can be improved for us all by for example Braille poker cards.

答:
Why would you change the current practice if it works? Braille cards might work (do they even exist?) but as those who don't know braille will have a hard time reading them you'd need a set that has both braille and printed numbers on it.

Depending on his level of impairment, you might be able to use a planning poker app on a tablet instead. I know such exist for Android, have seen them in use on smartphones, there's no reason why they shouldn't work on a 7" or 10" tablet as well. That would make the "cards" a lot larger for him than they are now, allowing him to hopefully see.

Of course there's the cost of the tablets, everyone in the team would need to have one for him to see everyone's cards (but same with braille cards, having him feel every card to sense what everyone put down would be at least as disruptive as everyone saying his number out loud).

So overall, I don't see a reason for the current practice to be changed. Have everyone say what his number is when casting his card, then the session leader averages those numbers to come up with the estimate.


问:
How to insert/update a large amount of data into mysql using php
I have an excel sheet which has a large amount of data. I am using php to insert the data into mysql server.

I have two problems

1) I have to update a row if the id already exists, else insert the data.

2) BIG PROBLEM : I have more than 40,000 rows and the time out on the sql server which is set by the admin is 60 seconds. When i run the update/insert query it will take more than 60 seconds, and because of this there will be a timeout. So the whole process will fail.

Is there a way I can do this ?

Currently I am checking the student id if it exists, then update otherwise insert. This I feel is taking a lot of time and causing the server to time out.

Also I have this field in the mysql stating the last time the data was updated(last_update). I was thinking of using this date, and if it is past a particular date(ie last time i ran the program) then only those rows should be updated.

Will this help in anyway ?

And what is the query i can run so as to check this date in the mysql database, that if it is past a particular date only those rows need to be updated and not everything else.
(Please help me with an example query for the above!!!!!!!!!!!!!!!!!)

答:
Use MySQL's INSERT... ON DUPLICATE KEY UPDATE syntax to automatically handle the insert/update logic. 40,000 is not that many rows - I'd be surprised if that command took more than a few seconds.

Note that you can insert many rows at once:

```<code>INSERT INTO table (id, name) VALUES (id1, name1), (id2, name2), ..., (idN, nameN) ON DUPLICATE KEY UPDATE id=VALUES(id), name=VALUES(name)
</code>```

If you're worried about hitting a memory limit (possible) then try loading the rows in batches of a few thousand at a time and looping through.

ContentLicense: CC BY-SA 3.0

Body:
Use MySQL's INSERT... ON DUPLICATE KEY UPDATE syntax to automatically handle the insert/update logic. 40,000 is not that many rows - I'd be surprised if that command took more than a few seconds.

Note that you can insert many rows at once:

INSERT INTO table (id, name) VALUES (id1, name1), (id2, name2), ..., (idN, nameN) ON DUPLICATE KEY UPDATE id=VALUES(id), name=VALUES(name)

If you're worried about hitting a memory limit (possible) then try loading the rows in batches of a few thousand at a time and looping through.


问:
How can I identify a namespace without using a string literal?
My team has a lot of IOC conventions that look something like...

```<code>if (type.Namespace == "My.Fun.Namespace")
{
    // do stuff
}
</code>```

Of course, maintaining this kind of thing becomes brutal after awhile, and we would rather not. The only option I could think of was to store these all in one place, as string constants or something of that nature, but that isn't a lot better... We have been considering making classes that basically serve as namespace identifiers in order to have almost an anchor type to key off of, like, say...

```<code>if (type.Namespace == typeof(My.Fun.Namespace.MarkerClass).Namespace)
{
    // do stuff
}
</code>```

But that just feels weird. So is there another way to solve this one that we just don't know about? If not, has anyone had any luck with the whole marker class concept?

答:
I think your second approach is the best solution. However, I understand that it looks weired to access the namespace by using another class as a reference. Maybe you can maintain a single file with many namespaces only containing a single interface.

```<code>namespace My.Fun.NameSpace
{
    interface IContract { }
}
namespace My.Other.NameSpace
{
    interface IContract { }
}
</code>```

usage:

```<code>if (type.Namespace == typeof(My.Fun.Namespace.IContract).Namespace)
{
    // do stuff
}
</code>```

Another option I could think of is an extension method

```<code>namespace System
{
    public static class TypeExtension
    {
        public static bool IsFromFunNameSpace(this Type type)
        {
             return IsFromNameSpace(type, typeof(My.Fun.NameSpace.IContract));
        }

        public static bool IsFromOtherNameSpace(this Type type)
        {
            return IsFromNameSpace(type, typeof(My.Other.NameSpace.IContract));
        }

        private bool IsFromNameSpace(Type type, Type contract)
        {
            type.Namespace == contract.NameSpace;
        }
    }
}
</code>```

usage:

```<code>if (type.IsFromFunNameSpace())
{
    // do stuff
}
</code>```

Anyway your IOC approach looks weired to me.
The ultimate solution (which requires you to have access to the source code) would be to just let a class implement an interface (which can be empty)

```<code>public interface IFun { }

public class FunnyClass : IFun { }
</code>```

usage:

```<code>if (typeof(IFun).IsAssignableFrom(type))
{
    // do stuff
}
</code>```

Now you are not limited to a specific namespace

Body:
I think your second approach is the best solution. However, I understand that it looks weired to access the namespace by using another class as a reference. Maybe you can maintain a single file with many namespaces only containing a single interface.

namespace My.Fun.NameSpace
{
    interface IContract { }
}
namespace My.Other.NameSpace
{
    interface IContract { }
}

usage:

if (type.Namespace == typeof(My.Fun.Namespace.IContract).Namespace)
{
    // do stuff
}

Another option I could think of is an extension method

namespace System
{
    public static class TypeExtension
    {
        public static bool IsFromFunNameSpace(this Type type)
        {
             return IsFromNameSpace(type, typeof(My.Fun.NameSpace.IContract));
        }

        public static bool IsFromOtherNameSpace(this Type type)
        {
            return IsFromNameSpace(type, typeof(My.Other.NameSpace.IContract));
        }

        private bool IsFromNameSpace(Type type, Type contract)
        {
            type.Namespace == contract.NameSpace;
        }
    }
}

usage:

if (type.IsFromFunNameSpace())
{
    // do stuff
}

Anyway your IOC approach looks weired to me.
The ultimate solution (which requires you to have access to the source code) would be to just let a class implement an interface (which can be empty)

public interface IFun { }

public class FunnyClass : IFun { }

usage:

if (typeof(IFun).IsAssignableFrom(type))
{
    // do stuff
}

Now you are not limited to a specific namespace


问:
What is the role of a product owner in scrum?
I am learning about Scrum and currently have a basic knowledge. I have a few questions about the role of the Product Owner in the Scrum process:

What is role of Product Owner in daily Scrum, if he/she is part of this meeting?

Product Owner is the person who is customer. A team member can be nominated as a proxy of product owner?

Can we say that a Project Manager who directly interacts with customer is nominated as proxy of Product Owner?

When we use term "External Stakeholders Engagement", are we referring to Product Owner or something else?

答:
The Product Owner does not have an active role in the daily stand-up meeting in Scrum. He/she can listen in to get a sense for what is going on in the team and how they are doing on their commitment.

The Product Owner should remain in the background during these meetings and not speak up. If the Product Owner has grave concerns, the he/she should take that up with the Scrum Master after the meeting.

If the Product Owner is present, it is possible they get asked for some clarification on some of the stories. Even that should be postponed until after the meeting in order to avoid draw out discussions during the stand-up.

If the actual customer can't be present often enough to take on the role of Product Owner, then a proxy can be nominated. The most important characteristics for the proxy are:

They have sufficient insight in what the customer actually wants to convey that vision to the team

They have enough authority to make decisions on the spot and to defend those decisions both to the team and to the customer.

Especially the second point usually means that the proxy must be either a very senior developer or someone from management circles.

I am not familiar with the term "External Stakeholders Engagement" (which is not a term used in Scrum), so I can't say definitively how it relates to a Product Owner, but at first glance the aim seems to be the same.


问:
New to Data Warehouses/ERP
The organisation I work for is very application rich i.e. there are lots of SQL and Oracle databases.  We are thinking about a data warehouse.

I believe there is a difference between an Enterprise Resource Planning system and a Data Warehouse.  An ERP would involve integrating all the systems together and having one database schema for everything.  A Data Warehouse would involve creating a copy database (or copy databases) for analysis reasons.  The Data Warehouse could extract information from the original repositories or the ERP system.

Have I understood this correctly?

Are there Data Warehouse products that are available to but or to you have to use Microsoft tools/Oracle tools e.g. SSIS, SSAS etc to write your own?

答:
ERP --> Purchase Ledger, Ordering + Stock Control

Data WareHouse --. Ad Hoc reporting

Or put it another way ERP is generally speaking an on-line system used by the many people in the company. There will usually be a work flow component as in the Foo department orders widgets which need approval from accounts, the order is actually placed by purchasing and the physical installation handled by building services.

A data warehouse is a cumulative copy of various significant data items from other systems in the company. And is used by management to track things like the monthly spend on widgets over the last two years.

Title: New to Data Warehouses/ERP


问:
Finding out which version of a file a line was added/changed
Is it generally possible while using source code management to figure out in what version of a file a specific line was added? If so, what SCM systems support this?</p>

答: It would be a poor version control system that didn't allow you to do this. A technical term for displaying the origin of lines by version is annotating a controlled file with its history. Recently, newer RCS like svn and git have switched to calling the action blame instead, but the functionality is the same. Searching for those two terms will tell you how to do it in your RCS of choice.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: Cowboy coders, big egos, and management acceptance thereof </p>

ContentLicense: CC BY-SA 2.5


问:
Being a good mentee - a protégé
The complement of the Being a good mentor question.

I work with many very senior people that have vast amounts of knowledge and wisdom in Software, Engineering and our business domain.

What are some tips for gaining as much knowledge from them?  I don't want to take up too much of their time, but also want to take full advantage of this since it really could help develop my skills.

What are some good questions to get the conversation rolling in a sit down mentor/mentee session?  Some of the people providing mentorship have little experience in this area, so it would help to be able to lead some of these discussions.

答: ask smart questions where you can. read before asking. see how much you can figure out for yourself. resort to spoonfeeding only when everything else fails.</p>

Title: Being a good mentee - a protégé


答:
Expanding on what James said, your live application databases would tend to be build for speed and for strict business rules to ensure data integrity. You might only keep a small amount of the total data in these databases at any particular time (e.g that last 2 days of customer activity), and the focus is on quick response and business integrity.

A data warehouse is generally build for size, with much less focus on speed and/or data integrity. Generally you try and store everything, the idea being that you don't know what you will need when you are storing it. These systems are not build for speed, as speed on a system that size would be impractical without investing millions in memory and solid state drives. As such they are never accessed by live customer facing applications (because they are so huge they would slow down these applications).

Instead they are build for queries that need access to large amounts of data to get the correct answer. A query on a data warehouse might take from a few seconds to a few days, depending on the complexity. When I worked in a bank we ran a lot of queries for the long term planning guys, to decide things like what customers to target for savings promotion, or to figure out the ideal place to put a new ATM. An example query on a data warehouse would be something like give me the home address of every customer with a current account who has accessed one of these 10 ATMs between 2000 and 2004 more than 3 times a week to withdraw more than $10. That query would be run over literally billions of records (millions of customers, billions of ATM interactions etc), and could take hours to run.

How you build your database and what software you use will depend largely on the type of data you are collecting.

For example if you are collecting logs from your applications, then there are specialist software for large collection of logs, such as Splunk and ElasticSearch

If you collecting a host of different data that doesn't really all match up in a nice neat fashion something like an Hadoop cluster. Hadoop works on plain text files by splitting the files over a lot of machines and then running small programs on the text files to gather the information you want. Hadoop is open source but there are a lot of companies that have build commercially supported products around Hadoop.

Of course a data warehouse can simply be a large database, such as MySQL, PostgreSQL or Oracle. This might be ideal if you already have all your data formatted into relational tables. In this case you simply copy your data to your data warehouse. MySQL, Oracle and PostgreSQL all have specific features tailored to running the databases as a data warehouse where the emphasis is on speed. A commercial database that specialises in data warehousing is Teradata.

Title: New to Data Warehouses/ERP

Body:
The organisation I work for is very application rich i.e. there are lots of SQL and Oracle databases.  We are thinking about a data warehouse.

I believe there is a difference between an Enterprise Resource Planning system and a Data Warehouse.  An ERP would involve integrating all the systems together and having one database schema for everything.  A Data Warehouse would involve creating a copy database (or copy databases) for analysis reasons.  The Data Warehouse could extract information from the original repositories or the ERP system.

Have I understood this correctly?

Are there Data Warehouse products that are available to but or to you have to use Microsoft tools/Oracle tools e.g. SSIS, SSAS etc to write your own?


问:
Reason to treat internal class variables and functions inside a class as "separate" entities
Note:  there is a similar question that addresses my subject:  Better style for member variables?

... but that question does not address "dealing with large legacy code base and comprehension of functions that grew too large".  I am looking for confirmation or rejection of whether my situation warrants it to be a is a good enough reason to adopt a practice of writing internal-to-the-class functions as if they were separate entities, with their appropriate parameters and return values.

My question

Variables internal to a class are considered to be scoped as "globals" within contains of that class.  As such, these variables do not need to be included explicitly as parameters to the class' internal functions.  Further, if internal functions return values that may belong to existing inside-class variables, those also do not need to be returned explicitly.  You can just refer to them via using this object.  But, is doing so a good practice?

My question comes from the context of refactoring a huge legacy codebase.  As such, when I see a function inside a class that goes like $this->IamACute3000LineFunctionDoingInsanelyCuteStuffInASpaghettiCodeLikeWay(), I have little clue as to which in-class "global" variables it needs to do its job, and what exactly it returns.  This makes it hard and time consuming to deal with that code when any work is to be done on the class.  Thus, even though it may not make sense inside the class itself, I do see some merit in writing code like below, treating variables and parameters as if the function was written to be used outside of the class itself:

class HelloClass
{
   $private $name;
   $private $greeting;

   public function __construct($name)
   {
       $this->name = $name;

       //line of interest
       $this->greeting = $this->prepGreeting($this-name);
   }

   //function of interest
   private function prepGreeting($name)
   {
      return "Hello, $name";
   }

   public function getGreeting()
   {
       return $this->greeting;
   }
}

$sayHello = new HelloClass("Dennis");
print $sayHello->getGreeting();
```

<p>Here, <code>prepGreeting</code> is the function in question.  Surely, it looks a bit ridiculous... as it barely takes advantage of built-in class mechanisms, if at all.  It can be rewritten as such instead (with appropriate other constructor changes as well, which are not shown):</p>

```   private function prepGreeting()
   {
      $this->greeting = "Hello, " . $this->name;
   }
```

But then you have to actually read the function's body to understand what it does, what it touches and what it returns.

My question is this:

in my example, where I am dealing with large code where understanding a function takes time, I think there is a good reason to write internal class functions as if they were separate, not belonging to the class, as it will be superior for understanding what goes on inside the function, and what it returns.  This function will be self-contained and as such, it will help a lot with refactoring.  I could pluck that function out, bend the way I need it to bend, move it to another class, if I have to, thus making it easier to work with the class itself.  But, in general, would you recommend such function-writing practice when writing/designing classes?

Or would you recommend instead to use built-in this object, treating internal to the class variables as "class globals", even though doing so may impact readability/understanding/comprehension of the function if its size does grow, as it often does in real life projects?

Finally, am I missing any greater points while focusing on this specific function-writing-style issue?

Add-on

I do see merit in perhaps using some middle-ground, where function parameters are not passed to the function (function uses this object to get to those), but the function still returns values, instead of updating this object directly, and it is up to the caller to update this variable.  i.e. this will change my "line of interest" to this code:  $this->greeting = $this->prepGreeting(); and at least I will know what the function is supposed to return, at a glance.

答:
Finally, am I missing any greater points while focusing on this specific function-writing-style issue?

Yup.

By the sounds of it the classes are way to big. Way way to big. If you can't figure out what a private method is doing just by looking at it, or what private variables are being called and what they are used for, it is a serious code smell that your classes are far to big and un-focused.

It should be obvious from the private method that it is updating the state of the object, and the object should have so little state that it should be obvious what it means to say that its state is being updated. If you have an object that has a whole ton of state that can be changed in different ways and you never know what sub-section of the state a method is going to be altering, again your objects are too big.

Of course you might not be able to control this if it is legacy code that you have inherited. But rather than re-factoring the methods it would make more sense to break up the classes themselves. Even your class above could be broken up into a Name class and a Greeting class, in which case the state of the objects becomes clearer (a Name class simply has the name, a Greeting class simply has the greeting)


问:
The best way to open source my website
I'm creating a website where trust is a big issue, I want to prove by making it open source I actually do what I claim.

Question 1. If I make my source code open, how can I prove the actual website runs on this code?

But I also have a dilemma, it is a commercial project and I don't want others to run off with it and claim it theirs. So I think I need a correct license.

Question 2. What license is best for me? Currently I'm thinking about GPL v3.

答:
You cannot prove that your server is running the code you have released. Therefor you also cannot prove that someone else is running the code you have released so you will have a difficult time stopping your competitors no matter what license you use.

The point of open source is that 3rd parties can deploy your code for their own purposes and then relay bug fixes and additional features back into the original project. Releasing the source code and declaring it open source will not magically make your system bugfree or secure if no one bothers looking at the code.

In a nut shell, releasing the source code but not letting anyone else use it is not what open source is about.

Title: The best way to open source my website


问:
Best example for mixins in .NET
I want to present the concept of mixins and their implementation in .NET.

The way they work in .NET is you add extension methods on an interface and decorate classes with said interface.

What would be the best examples for this pattern (other than linq)?

答:
I've been working on an open source Mixin framework for C# pMixins.  It leverages partial classes and code generators to wire in the Mixin class into the Target:</p>

```<code>//Mixin - Class that contains members that should be injected into other classes.
public class Mixin
{
   // This method should be in several class
   public void Method(){ }
}

//Target (Note: That it is partial) - Add members from Mixin
[pMixn(Target = typeof(Mixin)]
public partial class Target{}

//Example of using Target
public class Consumer
{
    public void Example()
    {
        var target = new Target();

        // can call mixed in method
        target.Method();

        // can implicitly convert Target to Mixin
        Mixin m = new Target();
        m.Method();
   }
}
</code>```

Title: Best example for mixins in .NET

Body:
I've been working on an open source Mixin framework for C# pMixins.  It leverages partial classes and code generators to wire in the Mixin class into the Target:

//Mixin - Class that contains members that should be injected into other classes.
public class Mixin
{
   // This method should be in several class
   public void Method(){ }
}

//Target (Note: That it is partial) - Add members from Mixin
[pMixn(Target = typeof(Mixin)]
public partial class Target{}

//Example of using Target
public class Consumer
{
    public void Example()
    {
        var target = new Target();

        // can call mixed in method
        target.Method();

        // can implicitly convert Target to Mixin
        Mixin m = new Target();
        m.Method();
   }
}


答:
As part of your refactoring efforts, encapsulating functions so that they perform their function with only parameters passed in is very useful.

It decreases coupling. In a large (especially in a large) class, with lots of fields, you have to consider them as globals, mostly because their accessibility and possibility of change are not local to the screen you see in front of you or the method you see in front of you. Moving from sharing "global variables" to passing parameters is a substantial improvement.

If you can reduce or remove side effects while you are at it, you address a similar aspect of coupling. Your function only returns a value or only calls an external method that is not dependent on the host class and you no longer have to manage your globals in the same way.

Title: Reason to treat internal class variables and functions inside a class as "separate" entities

Body:
Note:  there is a similar question that addresses my subject:  Better style for member variables?

... but that question does not address "dealing with large legacy code base and comprehension of functions that grew too large".  I am looking for confirmation or rejection of whether my situation warrants it to be a is a good enough reason to adopt a practice of writing internal-to-the-class functions as if they were separate entities, with their appropriate parameters and return values.

My question

Variables internal to a class are considered to be scoped as "globals" within contains of that class.  As such, these variables do not need to be included explicitly as parameters to the class' internal functions.  Further, if internal functions return values that may belong to existing inside-class variables, those also do not need to be returned explicitly.  You can just refer to them via using this object.  But, is doing so a good practice?

My question comes from the context of refactoring a huge legacy codebase.  As such, when I see a function inside a class that goes like $this->IamACute3000LineFunctionDoingInsanelyCuteStuffInASpaghettiCodeLikeWay(), I have little clue as to which in-class "global" variables it needs to do its job, and what exactly it returns.  This makes it hard and time consuming to deal with that code when any work is to be done on the class.  Thus, even though it may not make sense inside the class itself, I do see some merit in writing code like below, treating variables and parameters as if the function was written to be used outside of the class itself:

class HelloClass
{
   $private $name;
   $private $greeting;

   public function __construct($name)
   {
       $this->name = $name;

       //line of interest
       $this->greeting = $this->prepGreeting($this-name);
   }

   //function of interest
   private function prepGreeting($name)
   {
      return "Hello, $name";
   }

   public function getGreeting()
   {
       return $this->greeting;
   }
}

$sayHello = new HelloClass("Dennis");
print $sayHello->getGreeting();
```

<p>Here, <code>prepGreeting</code> is the function in question.  Surely, it looks a bit ridiculous... as it barely takes advantage of built-in class mechanisms, if at all.  It can be rewritten as such instead (with appropriate other constructor changes as well, which are not shown):</p>

```   private function prepGreeting()
   {
      $this->greeting = "Hello, " . $this->name;
   }
```

But then you have to actually read the function's body to understand what it does, what it touches and what it returns.

My question is this:

in my example, where I am dealing with large code where understanding a function takes time, I think there is a good reason to write internal class functions as if they were separate, not belonging to the class, as it will be superior for understanding what goes on inside the function, and what it returns.  This function will be self-contained and as such, it will help a lot with refactoring.  I could pluck that function out, bend the way I need it to bend, move it to another class, if I have to, thus making it easier to work with the class itself.  But, in general, would you recommend such function-writing practice when writing/designing classes?

Or would you recommend instead to use built-in this object, treating internal to the class variables as "class globals", even though doing so may impact readability/understanding/comprehension of the function if its size does grow, as it often does in real life projects?

Finally, am I missing any greater points while focusing on this specific function-writing-style issue?

Add-on

I do see merit in perhaps using some middle-ground, where function parameters are not passed to the function (function uses this object to get to those), but the function still returns values, instead of updating this object directly, and it is up to the caller to update this variable.  i.e. this will change my "line of interest" to this code:  $this->greeting = $this->prepGreeting(); and at least I will know what the function is supposed to return, at a glance.


问:
Why is Python used for high-performance/scientific computing (but Ruby isn't)?
There's a quote from a PyCon 2011 talk that goes:

At least in our shop (Argonne National Laboratory) we have three
  accepted languages for scientific computing. In this order they are
  C/C++, Fortran in all its dialects, and Python. You’ll notice the
  absolute and total lack of Ruby, Perl, Java.

It was in the more general context of high-performance computing. Granted the quote is only from one shop, but another question about languages for HPC, also lists Python as one to learn (and not Ruby).

Now, I can understand C/C++ and Fortran being used in that problem-space (and Perl/Java not being used). But I'm surprised that there would be a major difference in Python and Ruby use for HPC, given that they are fairly similar. (Note - I'm a fan of Python, but have nothing against Ruby).

Is there some specific reason why the one language took off? Is it about the libraries available? Some specific language features? The community? Or maybe just historical contigency, and it could have gone the other way?

答: One reason is that Python has good support for using/integrating/calling C/C++ code, whereas to my knowledge Ruby does not offer the same degree of (ease of) integration.  This means that you can write the high-performant code components in C/C++, and then use Python (i.e a high-level / easier-on-the-eyes language) to glue the whole thing together.  I imagine that this is also one of the reasons for its early institutional adoption by Google.</p>


问:
Is allocating objects from a memory-pool a security anti-pattern?
In the wake of the heartbleed bug, OpenSSL has been rightly critizised for using its own freelist.  With plain-old malloc, the bug would have almost certainly been found long ago.

However, some kind of malloc wrapping is actually very common.  For example when I have a big object that owns many small, fixed sized objects, I often allocate them from an array.

```<code>/* BigObj is allocated with `malloc`, but LittleObj using `alloc_little`. */
typedef struct {

    /* bigObj stuff here */

    int nlittle;
    LittleObj littles[MAX_LITTLE];
} BigObj;

LittleObj *alloc_little(BigObj *big)
{
    if(big->nlittle == MAX_LITTLE)
        return NULL;
    return = big->littles + big->nlittle++;
}
</code>```

alloc_little is faster than malloc(), but the main reason is simplicity.   There is no free_little to call, because the LittleObjs just remain valid until the BigObj is destroyed.

So is this an anti-pattern?  If so, can I mitigate the risks, or should I just abandon it? Similar questions go for any kind of memory pool, such as GNU Obstacks and the talloc used in Samba.

答:
No.

C is not safe. C is not friendly. C does not catch your errors for you. As you say, using a different allocator might have caught the error sooner - but it would not have prevented it in the first place, at the design stage. The same or a similar error would likely still have been made, and while other strategies might have helped catch it sooner, it would still be after the fact.

The antipattern is in forgetting this and designing code that can potentially overflow or make invalid accesses in the first place, that doesn't either check what it's being asked to do or prove it won't do anything dangerous at compile-time. So there is an antipattern here if you just "don't track" a LittleObj: deal with this by being able to prove where their owners are at all times (and that it's mechanically impossible for the owner of a LittleObj to outlive its associated pool), not by hoping undefined behaviour will point out a mistake later.

Ruling this sort of technique out as an antipattern makes it less easy to use C for one of its strengths: implementing low-level, unsafe, runtime details so that higher-level languages and systems can be built on top of it (not every GC or other runtime can be built on malloc effectively). If in doubt, better not to be using C for the complex high-level stuff at all - leave it to an altogether safer system rather than trying to hammer C into a tool it isn't, and let a machine prove or ensure that your program is safe (stricter programming language, restrictive API, machine-checkable spec, etc.). Otherwise what would we implement low-level features in?

The ultimate counterexample is probably the ML Kit, whose C-implemented backend uses regions - a much more advanced form of the same basic idea as pools - combined with the ironclad SML type system to prevent invalid memory accesses.

OwnerDisplayName: Adrian Ratnapala

OwnerDisplayName: Leushenko


问:
MVC4 : How to create model at run time?
In my project I am dynamically creating table by giving table name (ex. student) and adding fields to that table and then save table. Now, my table is created in SQL Server database.

Assume table has data and I want to show the data of table (ex student) on WebGrid. But, the problem is I have no model for that table (ex. student). So, how I can create model for newly created table or how I can show the the data on WebGrid?

答:
Not the best solution, but should work.

To display table data, only input you have is name of the table. So you will do

```<code>string sql = "SELECT * from " + tableName;
</code>```

And then fill a DataSet and then convert DataSet to List<List<string>> object like in this answer. Pass that on to your view. Loop through it in the view to display tabular data. The caveat here is that you will handle all datatypes as string.

I don't think you will be able to use WebGrid

Title: MVC4 : How to create model at run time?

Body:
Not the best solution, but should work.

To display table data, only input you have is name of the table. So you will do

string sql = "SELECT * from " + tableName;

And then fill a DataSet and then convert DataSet to List<List<string>> object like in this answer. Pass that on to your view. Loop through it in the view to display tabular data. The caveat here is that you will handle all datatypes as string.

I don't think you will be able to use WebGrid


答:
of cause, it's not an anti-pattern, it's just one more way to fire in your leg

it can be usefull or can be not usefull, depending on usage scenario

there are a lot of technics to use statically pre-allocate memory (and not use malloc/free) and such technics often use in embedded devices

but, using such technics you should clearly understand will be possible to expose data to another user of your application. for example, if you use pre-allocated memory to dram primitives on screen - it's generally safe, if you use such memory to return signed (by key stored in some crypto storage) data - you have to wipe data before returning memory record to user.

I mean, then someone calls your alloc_little() you returns some memory and it can contains previous data. If your code doesn't operate with some sensitive data (it's really very hard to specify what IS a sensitive data) - you can don't clean the memory. If you think, data operated inside LittleObj is sensitive - you have to clear this memory before usage.

Moreover, you have to track all allocated memorries, because on can call alloc_little()/free_little() and keep address of struct. and periodically poll it for information.

SO, it's not an antipattern, it's veru usefull technic on some cases but you should clearly understand what do you do and who can access this memory.

Title: Is allocating objects from a memory-pool a security anti-pattern?

Body:
In the wake of the heartbleed bug, OpenSSL has been rightly critizised for using its own freelist.  With plain-old malloc, the bug would have almost certainly been found long ago.

However, some kind of malloc wrapping is actually very common.  For example when I have a big object that owns many small, fixed sized objects, I often allocate them from an array.

```<code>/* BigObj is allocated with `malloc`, but LittleObj using `alloc_little`. */
typedef struct {

    /* bigObj stuff here */

    int nlittle;
    LittleObj littles[MAX_LITTLE];
} BigObj;

LittleObj *alloc_little(BigObj *big)
{
    if(big->nlittle == MAX_LITTLE)
        return NULL;
    return = big->littles + big->nlittle++;
}
</code>```

alloc_little is faster than malloc(), but the main reason is simplicity.   There is no free_little to call, because the LittleObjs just remain valid until the BigObj is destroyed.

So is this an anti-pattern?  If so, can I mitigate the risks, or should I just abandon it? Similar questions go for any kind of memory pool, such as GNU Obstacks and the talloc used in Samba.


问:
Difference between REST and CRUD
I learned REST and it feels a lot like CRUD (from what I have read about CRUD).

I know they are different, and I wonder if thinking they are similar means I don't understand them.

Is it that REST is a "superset" of CRUD?  Does it do everything CRUD does and more?

答:
REST stands for "representational state transfer", which means it's all about communicating and modifying the state of some resource in a system.

REST gets quite involved, because the theory behind REST gets into leveraging media, hypermedia, and an underlying protocol to manage information on a remote system.

CRUD, on the other hand, is a mnemonic for the common operations you need for data in a database: Create Retrieve Update Delete. But it really doesn't get any deeper than that.

So that's the answer to your question, but I'll mention the common mistake I see when REST and CRUD are discussed together. A lot of developers want to map REST to CRUD directly, because REST over HTTP provides for GET PUT POST and DELETE, while CRUD provides for CREATE RETRIEVE UPDATE DELETE. It's natural to want to map the REST verbs directly to CRUD operations.

However, HTTP uses a "create or update" style, while CRUD separates create and update. That makes it impossible (!) to make a clean, general mapping between the two (!)

GET and DELETE are easy... GET === RETRIEVE, and DELETE === DELETE.

But per the HTTP spec, PUT is actually Create AND Update:

Use PUT to create a brand new object when you know everything about it, including its identifier

Use PUT to update an object (usually with a complete representation of the object)

POST is the "processing" verb, and is considered the "append" verb:

Use POST to append a new object to a collection -- that is, create a new object

POST is also used when none of the other verbs quite fit, as the HTTP spec defines it as the "data processing" verb

If your team is getting hung up on POST, remember that the entire WWW was built on GET and POST ;)

So while there is similarity between REST and CRUD, the mistake I see most teams make is to make an equivalence between the two. A team really needs to be careful when defining a REST API not to get too hung up on the CRUD mnemonic, because REST as a practice really has a lot of additional complexity that doesn't map cleanly to CRUD.

ContentLicense: CC BY-SA 4.0

Title: Difference between REST and CRUD


答:
You can query that dynamic table and fetch those results into a DataTable the traditional way.

After this you can seralize this into a json string. https://stackoverflow.com/a/12063095/145682 ... shows you how.

These can then be easily consumed by js libraries like knockout.js, or, jquery, etc and rendered on the Web page.

Title: MVC4 : How to create model at run time?

Body:
In my project I am dynamically creating table by giving table name (ex. student) and adding fields to that table and then save table. Now, my table is created in SQL Server database.

Assume table has data and I want to show the data of table (ex student) on WebGrid. But, the problem is I have no model for that table (ex. student). So, how I can create model for newly created table or how I can show the the data on WebGrid?


问:
Should MVVM ViewModel inject an HTML template for default view?
I'm working on web application design that includes Knockout.js and have an overall MVVM question: Does it make sense for the ViewModel to automatically inject a default HTML template (pulled from separate file)?

More detail: suppose I have a site like this...

```<code>header...
    widget 1
    widget 2
    widget 3
footer
</code>```

...and widgets 1/2/3 are going to be Knockout.js ViewModels determined at runtime from an overall list of available widgets, each with associated HTML template file. I understand that in MVVM you want the view (HTML template in this case) to be separate from the ViewModel (Javascript file in this case) so that people can edit it separately and possibly provide multiple templates for different "skins". However, it seems like it would also make sense for the ViewModel to point to a default html template that gets automatically used unless the controlling code provides a different one.

Am I looking at this correctly?

As an example, see this answer on StackOverflow where he recommends injecting the HTML and then the ViewModel. Seems like a one-liner would make more sense in that case, with the possibility of overriding a default template value.

答:
MVVM doesn't have a strict definition, I use the one described by Microsoft (as understood by me, each one has their own ideas on it).

One of his main goal is to abstract the view from the viewmodel, and one of main rules is 'only views should call other views, because ViewModel should not know anything about his view'.

So to give a simple theoretical answer: I think when loaded, your view should ask the viewmodel the list of widgets to load and then your view should load the corresponding widgets.

This way, logic is handled by the ViewModel, and only a view calls other views.


答:
An ERP may be a single product line like SAP, Oracle,  (with many sub modules), but it can be separate applications (by manufacturer and technology stack), but are integrated. Data may transfer from one database schema to another. Example would be using SalesForce.com to handle the acquisition of new business but an accounting app is used to manage the billing/post closing of the account.

The data warehouse is build more for reporting (denormalized) and not managing transactions (more normalized). There can also be snapshots for different periods for trending and other point-in-time analysis. Many BI tools work better in these environments.

You may find some ERP systems have a data warehouse component. There are probably data warehouses that are industry specific, but would still need a lot of setup and possible customization. Another benefit is these companies would have inhouse expertise for the technology and industry.

I realize terminology can help with communication, but I would decide on what your needs are and then find solutions. These are very general terms with many meanings. Personally, I'd rather call it Project X than have a bunch of people call it ERP when there is a large data warehouse component.

Title: New to Data Warehouses/ERP


问:
What is the good way of sharing specific data between ViewModels
We have IAppContext which is injected into ViewModel.

This service contains shared data: global filters and other application wide properties.

But there are cases when data is very specific. For example one VM implements Master and the second one - Details of selected tree item. Thus DetailsVm must know about the selected item and its changes.

We can store this information either in IAppContext or inside each concerned VM. In both cases update notifications are sent via Messenger.

I see pros and cons for any of the approaches and can not decide which one is better.

1st:

+ explicitly exposed shared properties, easy to follow dependencies

- IAppContext becomes cluttered with very specific data.

2nd:

the exact opposite of the first and more memory load due to data duplication.

May be someone can offer design alternatives or tell that one of the variants is objectively superior to the other cause I miss something important?

答:
I hope this answer will benefit others that reach that question, because by timestamp alone I think OP solved the problem long ago. ;-)
The post doesn't present immediate solution (I'd need more data from OP for that), but offers some pointers instead.

Parent-child

As mentioned in comments (first by @Rachel), for hierarchical data there's a parent-child relationship.

Uncertainty principle

As with pretty much any design decision, there's the uncertainty principle: hold off with deciding, as long as possible. Implement both and keep them going and see which suits your case better. I should note here I'm not versed AT ALL in WPF, but that sentence:

I see pros and cons for any of the approaches and can not decide which one is better.

strongly indicates laying off decision till you see one approach yields better results than the other will work for you.

It depends

Since there's little information about use cases and amount of shared / specific data, I'll propose some things based on assumptions.

Assuming very different, always case-specific extra data

For each case, create a property file or value objects that can store extra data.

Add mechanism allowing AppContext to pull said property file / value object in by name / id / other.

VMs requiring this should be able to tell AppContext to pull that data when they're initialized. This may even be done via naming convention.

Assuming very different, partially reusable extra data

Proceed as in previous case. Why despite this advice I'm marking this as a separate section? Because in cases of just partial reuse I often find it prudent to just skip reuse at all:

partial reuse tempts, but rarely it really is worth the time spent on thinking "how to reuse it well"

if you botch the reuse, end-result is rarely maintainable

newbies coming to code will be quite confused when they SHOULD reuse and when not and HOW to reuse

Bottom line: clarity suffers. If you aren't sure data will be reused, don't bother.

Assuming great deal of extra data, lots of different cases, significant reuse

Split the app. There's obviously too many apps trying to fit here and patterns you identified may be different domains. At this point I'd took a closer look at DDD patterns (especially Bounded Context) and would consider moving the real shared data from IAppContext to supporting domain.


问:
What are some effective ways of making scrum more dynamic earlier in a sprint?
My team does 2-week sprints, and the trend we've identified (which we want to move away from) is that our daily standup scrums are relatively straightforward early in the sprint, but then transform into a more frantic scramble toward the end.

The first week developers are heads down in coding, analysts are developing test plans and answering developer questions, and testers are refining existing tests and identifying areas to test (but not necessarily testing just yet since there isn't as much out there actually ready to test). Blockers and scope creep tend to emerge into the second week, and then as we see how close we're getting to the end, we force ourselves to make tough choices and be more communicative.

How can we "spread the wealth" and increase the overall "tempo" (I guess?) of our scrums from the beginning of the sprint to the end?

答:
Blockers and scope creep tend to emerge into the second week

Oh, Hell No! Stop the sprint immediately. This will not stand. Product Owners need to understand the consequences of interrupting a sprint. We have to start all over.

Find out if there was a way to avoid this problem (Did we missing something.). Go through the start of a new sprint. This will smooth out the "highs" in the project so afterwards everyone won't feel so low. Smooth and steady. No panic. No death march every 2 weeks.

Standups - I don't care if you had your head down in code all day yesterday, what did you do?, what are you going to do today? It's not fancy and no need to be entertained. Stay awake everyone for 15 minutes - it's not that hard. Everyone should still be jazzed-up that they had to redo the sprint.

Just because they're called sprints doesn't mean the project isn't a marathon.


问:
Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.

答:
There are lots of good answers here; Stephen's answer in particular does a good job of illustrating why violations of the substitution principle lead to real-world conflicts between teams.

I thought I might talk briefly about the specific problem of rectangles and squares, rather than using it as a metaphor for other violations of the LSP.

There is an additional problem with square-is-a-special-kind-of-rectangle that seldom gets mentioned, and that is: why are we stopping with squares and rectangles?  If we are willing to say that a square is a special kind of rectangle then surely we should also be willing to say:

A square is a special kind of rhombus -- it's a rhombus with square angles.

A rhombus is a special kind of parallelogram -- it's a parallelogram with equal sides.

A rectangle is a special kind of parallelogram -- it's a parallelogram with square angles

A rectangle, square and parallelogram are all a special kind of trapezoid -- they are trapezoids with two sets of parallel sides

All of the above are special kinds of quadrilaterals

All of the above are special kinds of planar shapes

And so on; I could keep going for some time here.

What on earth should all of the relationships be here? Class-inheritance-based languages like C# or Java were not designed to represent these sorts of complex relationships with multiple different kinds of constraints. It's best to simply avoid the question entirely by not trying to represent all of these things as classes with subtyping relationships.


问:
Is it okay to not completely understand code functionality?
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?

答:
As most of the time, it all depends. At the extreme end, there is the use of a library. You are not supposed to know or care how it works. You are supposed to know what to put in and what comes out, what it can and what it cannot do.

At the other end, you don't know how to do some task because you haven't done it before. You find ten lines of code on the internet, which seems easier than finding the right information in your documentation (and often is). At that point I'd strongly suggest that now is the right time to learn how to do that task. So take the code, understand it, make it your own. Realise that lots of code on the internet isn't necessarily written by the cleverest of people, so there may be weaknesses and misunderstanding, so by learning now you can make sure that the code works. And at the point where you include those ten lines in your project, they are your responsibility. If the code doesn't work, it's your fault. So you have to understand it, as if you had written it.

So what's the difference to the library? Isn't that your responsibility as well? The code of the library isn't. The choice of library and the usage of the library is. If the library crashes your application ten times a day, that's because you picked a library that is unreliable. You don't have to understand the code of the library, but you have to understand its reliability issues and act.


答:
Your problem looks like the typical "waterfall in each sprint", if you do the real testing in the second week the problems appear in the second week.

In my experience there are various areas you can improve:

Make small user histories, one or two days per history perhaps, this way at the end of the first week you have some US completely developed and tested.

Revise your technical practices. Agile don't work only with post-its, the team its using properly techniques like TDD or continuos integration? (this two are fundamental for checking assumptions earlier in the process and don't have this "at the last moment all problems emerge" symptom).

Your talk about analyst, testers and developers, looks like a lot of specialization. This its not bad in itself, depend in a lot of factors, but perhaps you need to do something to improve the communication from the first day of sprint, for example try developers pair with business analyst or testers.

And the most important: use the retrospectives to discuss this problems, what the team thought?, what solutions they propose?. At the end of the day your solution its inside your team not in stack overflow :P

Title: What are some effective ways of making scrum more dynamic earlier in a sprint?

Body:
My team does 2-week sprints, and the trend we've identified (which we want to move away from) is that our daily standup scrums are relatively straightforward early in the sprint, but then transform into a more frantic scramble toward the end.

The first week developers are heads down in coding, analysts are developing test plans and answering developer questions, and testers are refining existing tests and identifying areas to test (but not necessarily testing just yet since there isn't as much out there actually ready to test). Blockers and scope creep tend to emerge into the second week, and then as we see how close we're getting to the end, we force ourselves to make tough choices and be more communicative.

How can we "spread the wealth" and increase the overall "tempo" (I guess?) of our scrums from the beginning of the sprint to the end?


问:
Handling Coding Standards at Work (I'm not the boss)
I work on a small team, around 10 devs. We have no coding standards at all. There are certain things that have become the norm but some ways of doing things are completely disparate. My big one is indentation. Some use tabs, some use spaces, some use a different number of spaces, which creates a huge problem. I often end up with conflicts when I merge because someone used their IDE to auto format and they use a different character to indent than I do. I don't care which we use I just want us all to use the same one.

Or else I'll open a file and some lines have curly brackets on the same line as the condition while others have them on the next line. Again, I don't mind which one so long as they are all the same.

I've brought up the issue of standards to my direct manager, one on one and in group meetings, and he is not overly concerned about it (there are several others who share the same view as myself). I brought up my specific concern about indentation characters and he thought a better solution would be to, "create some kind of script that could convert all that when we push/pull from the repo." I suspect that he doesn't want to change and this solution seems overly complicated and prone to maintenance issues down the road (also, this addresses only one manifestation of a larger issue).

Have any of you run into a similar situation at work? If so, how did you handle it? What would be some good points to help sell my boss on standards? Would starting a grass roots movement to create coding standards, among those of us who are interested, be a good idea? Am I being too particular, should I just let it go?

Thank you all for your time.

Note: Thanks everyone for the great feedback so far! To be clear, I don't want to dictate One Style To Rule Them All. I'm willing to concede my preferred way of doing something in favor of what suits everyone the best. I want consistency and I want this to be a democracy. I want it to be a group decision that everyone agrees on. True, not everyone will get their way, but I'm hoping that everyone will be mature enough to compromise for the betterment of the group.

Note 2: Some people are getting caught up in the two examples I gave above. I'm more after the heart of the matter. It manifests itself with many examples: naming conventions, huge functions that should be broken up, should something go in a util or service, should something be a constant or injected, should we all use different versions of a dependency or the same, should an interface be used for this case, how should unit tests be set up, what should be unit tested, (Java specific) should we use annotations or external config. I could go on.

答:
There are some things that are painful. Most painful is an IDE that automatically reformats code, combined with developers that set up their IDEs in different ways. Every time you compare code you have hundred changes after someone with different settings edited the code. That's unacceptable. Here you need to bang everyone's heads together, agree on a set of settings, and reject any checkins by anyone using different settings. If I change a single line of code, the diffs should show a single line of code changed, and not hundreds.

Everything else is either harmless, or there are better ways to do things that others can be convinced of. Here the rule should be: Don't mess with other people's code unless you really improve it. And a mix of style A and style B is always worse than both style A or style B.

Make sure you follow best practice. Which is different per language. But there you don't need standards (which may have been written by someone well-meaning but not actually that knowledgable), but everyone should try to give good examples.

Definitely avoid power struggles. There is nothing worse than some little Hitler in your team trying to force everyone to his will. And that's unfortunately the guy who will volunteer to write your coding standards :-(


问:
Object Identity and Mutability
I was reading a proposal for value types in Java, and I came across this sentence: "Object identity serves only to support mutability, where an object’s state can be mutated but remains the same intrinsic object."

From what I understand (albeit tentatively), object identity is the idea of your variable acting as a pointer or reference to an object located elsewhere in memory (such as objects instantiated on the heap in Java or C#). So what would this have to do with object mutability? Does this imply that, for example, instantiated objects on the stack in C++ are immutable? I'm having trouble seeing the link here.

答:
Object identity does not exist "only" to support mutability, but has other uses as well [indeed, an instance of Object type is useful only as an identity token, since it has no observably-mutable attributes whatsoever!]  Instead, identity is an often-unwanted characteristic that a mutable object will acquire any time there exist multiple references to the object, they are not all controlled by a single owner, and entities outside the owner might--without the owner's knowledge--make or see changes to that object.

Suppose that some static field X holds a reference to single-element instance of int[], and X[0]=5.  Static field Y also holds an element to a single-element instance of int[], and Y[0]=5.  If code ever calls IdentityHashCase() on X and Y, or if code tests X==Y, it will be able to discern whether X and Y identify the same instance of int[] or different instances.  Likewise, if code does something like X[0]+=1; Y[0]+=2;, the behavior will depend upon whether X and Y identify the same instance or different instances.  If, however, code never tests X and Y explicitly for reference equality, nor checks their identity hash code, or does anything else "reference-related", and if X[0] and Y[0] are never modified, then X and Y will be equivalent regardless of whether they identify the same arrays or different arrays.

One of the nasty things about identity in Java or .NET is that the identity of an object fundamentally depends upon the whereabouts of every entity in the universe that might make or see changes to that object.  If a reference to an object is ever freely exposed to outside code, the owner of the object will lose control over it and never be able to get it back.

Value types, unlike objects, can never be observed or modified except by the object or method wherein they are declared.  Thus, an object which holds a value-type field doesn't have to worry about losing control over it, since it is semantically impossible for that to happen.  In .NET (though not Java) it's possible to pass a variable, field, array element, or other storage location as a "reference parameter".  Doing so will temporarily allow the method to observe or modify the contents of the passed storage location for the duration of its execution, but any passed "byref" (the technical term for what is passed) is guaranteed to be destroyed before the method returns, thus ensuring that the caller maintains control over the data held therein, and ensuring that the container for that data won't acquire an unwanted identity.

Title: Object Identity and Mutability


问:
Bitwise-OR vs Adding Flags
I've seen others use Bitwise-OR to combine flags before:

```<code>#define RUN 0x01
#define JUMP 0x02
#define SHOOT 0x04

const byte madPerson = RUN | JUMP | SHOOT;
</code>```

That's also the way I do it.

But I've also seen some (not as many) combine flags using addition:

```<code>#define RUN 0x01
#define JUMP 0x02
#define SHOOT 0x04

const byte madPerson = RUN + JUMP + SHOOT;
</code>```

Which one is more "readable"? (Which one do you think more people will recognize?) What is the "standard" way to do it? Which one do you prefer?

答:
bitwise-OR conveys the intent more clearly

also, bitwise-OR should be more efficient

Title: Bitwise-OR vs Adding Flags


问:
Deleting Old Nuget Package Folders after upgrading
Should you delete the old Nuget package files/folders under the packages directory after you upgrade a package?

Maybe I'm just being overly picky, but seeing files/folder for older package versions it bothering me.  Is there a good reason NOT to delete the package folders for previous package versions?

答:
NuGet should remove old versions when upgrading, without any specific user intervention. If, for some reason, the old versions still exist after upgrade then they're safe to remove since there's no reason to keep them there.

I'm assuming that the upgrade is done through update-package command.


问:
Should my source code be in UTF-8?
I feel that often you don't really choose what format your code is in. I mean most of my tools in the past have decided for me. Or I haven't really even thought about it. I was using TextPad on windows the other day and as I was saving a file, it prompted me about ASCII, UTF-8/16, Unicode etc etc...

I am assuming that almost all code written is ASCII, but why should it be ASCII? Should we actually be using UTF-8 files now for source code, and why? I'd imagine this might be useful on multi-lingual teams. Are there standards associated with how multilingual teams name variables/functions/etc?

答:
Being able to type plain text into quoted strings or characters in source code and being able to see the actual character is very nice. For example the pi symbol 'π' or the ideograph '' are much nicer than the equivalent '\u3c0' for pi and L'\u2000A' for the ideograph.

It is possible to type and/or copy and paste these characters directly into source code, just as you would ASCII characters, in a decent editor.

I find concrete examples helpful in conceptualizing and understanding things that word descriptions sometimes don't seem to drive home. Conceptualize Unicode character constants typed into the source code, such as the following brief example code snippet:

```<code>const unsigned char  ASCII_0X7E      = (unsigned char)  '~';
const unsigned short UNICODE_0X3C0   = (unsigned short) 'π';
const unsigned long  UNICODE_0X2000A = (unsigned long)  '';
const unsigned long  UNICODE_0X2893D = (unsigned long)  '';
</code>```

The ASCII tilde character '~' can be saved in an ASCII or UTF-8 source file, but the Unicode characters are not able to be stored in ASCII form. The PI symbol 'π' is Unicode code point 0x3c0 and can be stored in UTF-8 form as a two byte value 0xcf, 0x80. The Ideographs at Unicode code points 0x2000a and 0x2893d require 4 byte UTF-8 sequences.

In order for those characters to retain their intended values and the compiler to interpret them as intended, the source code needs to be saved in a format that supports the Unicode character set, such as UTF-8 or UTF-16. If saved as UTF-8, a decent compiler will understand and interpret be the values as intended and a decent editor will load and display the characters properly.

As others have been pointing out, if you simply do not have any characters in your source code that are outside of the ASCII range, saving as UTF-8 will result in a file that is no different from saving an ASCII file, since UTF-8 is designed to overlap ASCII in the ASCII range of characters. As soon as you type any character into your source code that is outside the ASCII range, a decent editor will inform you that you have to pick an encoding to use to save the file. UTF-8 is a good choice since it can handle ASCII as is and virtually every other character supported in your development environment.

Title: Should my source code be in UTF-8?

Body:
Being able to type plain text into quoted strings or characters in source code and being able to see the actual character is very nice. For example the pi symbol 'π' or the ideograph '' are much nicer than the equivalent '\u3c0' for pi and L'\u2000A' for the ideograph.

It is possible to type and/or copy and paste these characters directly into source code, just as you would ASCII characters, in a decent editor.

I find concrete examples helpful in conceptualizing and understanding things that word descriptions sometimes don't seem to drive home. Conceptualize Unicode character constants typed into the source code, such as the following brief example code snippet:

const unsigned char  ASCII_0X7E      = (unsigned char)  '~';
const unsigned short UNICODE_0X3C0   = (unsigned short) 'π';
const unsigned long  UNICODE_0X2000A = (unsigned long)  '';
const unsigned long  UNICODE_0X2893D = (unsigned long)  '';

The ASCII tilde character '~' can be saved in an ASCII or UTF-8 source file, but the Unicode characters are not able to be stored in ASCII form. The PI symbol 'π' is Unicode code point 0x3c0 and can be stored in UTF-8 form as a two byte value 0xcf, 0x80. The Ideographs at Unicode code points 0x2000a and 0x2893d require 4 byte UTF-8 sequences.

In order for those characters to retain their intended values and the compiler to interpret them as intended, the source code needs to be saved in a format that supports the Unicode character set, such as UTF-8 or UTF-16. If saved as UTF-8, a decent compiler will understand and interpret be the values as intended and a decent editor will load and display the characters properly.

As others have been pointing out, if you simply do not have any characters in your source code that are outside of the ASCII range, saving as UTF-8 will result in a file that is no different from saving an ASCII file, since UTF-8 is designed to overlap ASCII in the ASCII range of characters. As soon as you type any character into your source code that is outside the ASCII range, a decent editor will inform you that you have to pick an encoding to use to save the file. UTF-8 is a good choice since it can handle ASCII as is and virtually every other character supported in your development environment.


问:
Find second largest element in a array?
The problem is to solve it in n+logn−2 (base 2) no of comparisons.

My algorithm is taking some extra space less then (O(n*n)). How can i reduce this extra space without increasing the complexity.

```<code>    comparisionarray=[][] (2D array )

    //a function to find the largest.
    findlargest(a,b)
       if(len(a)==1 and  len(b)==1)
          append b to array at ath index in comparisonarray.
          append b to array at bth index comparisionarray.
          return max(a,b)
       else
          return max(findlargest(1stHalfof(a),2ndHalfof(a)),findlargest(1stHalfof(b),2ndHalfof(b))

    input= input_array()
    largest=findlargest(1stHalfof(input),2ndHalfof(input))
    subarray=[array at index largest in comparisionarray]
    2ndlargest=findlargest(1stHalfof(subarray),2ndHalfof(subarray))
    print(2ndlargest)
</code>```

Edit:  It can be done in minimum n+logn−2 comparisons. That is the only condition . This answer on math.stackexchange.com proves it. It has been generalized for nth largest element

Seems that there is a solution at this link stackoverflow. But i am not sure about the extra space and time complexity.

答: I think the problem definition could use a bit of work..  Given the assumption that the data isn't sorted I don't see any reason why you can't solve this in effectively 2n comparisons at most, with basically constant memory..  As you read the array you keep two variables.  One holds the greatest value you've found so far the other keeps the second greatest.  Every time you find a new maximum push the old one down to the second variable.</p>

Title: Find second largest element in a array?


问:
How do I simplify a compiler/interpreter?
Recently I wrote an interpreter for operations on sparse matrices (a "sparse matrix calculator") in lex/yacc.  The language is still very bare bones and doesn't even include control structures or parameterized subroutines, yet it is already at several thousand lines of code, and that's not including the matrix classes.  In particular, the yacc file is close to two thousand lines in length.  Because of this I'm finding it quite difficult to work on.  Is this normal or is there a way I can simplify things?

If you want to review my code, it can be found at:
http://sourceforge.net/projects/msci/files/libpetey/

答:
A few thousand lines for a parser + interpreter that actually does something interesting is not unusual in the least. I looked at the SVN repo and especially your main grammar and noticed various things:

You have various utility classes that would make more sense in a general algorithms library. A quicksort implementation, really? IIRC, the C++ standard library already contains such functionality.

In general, the code seems to be very C-like (aside from the use of classes) and could benefit from building convenient abstractions using the vast array of C++ language features. I see a lot of code reuse via copy&paste.

You do not seem to build an AST, but parsing and evaluation happen at the same time. You should decouple parsing from semantic validation from interpretation. Once your yacc grammar only contains a grammar and not half an interpreter, it should become much more maintainable.

Separating the interpreter from the parser also has the advantage that it's easier to implement complex control flow such as loops, conditionals, or function calls.

Your grammar also includes help messages as string literals. Factor such messages out into a resources file, rather than hardcoding everything.

This was just a quick design review. If you're interested in an in-depth criticism of your code, post an excerpt of your code to Code Review.


答:
It looks like you're trying to do some sort of divide-and-conquer that you might find in a sorting algorithm.  Sorting and taking the second value from the large end would work, but it's overkill for this problem because you don't really need to have the set of elements sorted when you're done.

The brute-force solution is O(n-1), does at most 2*(n-1) comparisons and occupies space equivalent to two of your set members:

```<code>l1 := first_member_in_set  -- Largest value
l2 := first_member_in_set  -- Second-largest value

for each set member m after the first
    if m > l1
        l2 := l1
        l1 := m
    else if m > l2
        l2 := m
    end if
end for
</code>```

Note that for this to work (and for there to be a second-largest member at all), the set must have at least two members.

Title: Find second largest element in a array?

Body:
The problem is to solve it in n+logn−2 (base 2) no of comparisons.

My algorithm is taking some extra space less then (O(n*n)). How can i reduce this extra space without increasing the complexity.

```<code>    comparisionarray=[][] (2D array )

    //a function to find the largest.
    findlargest(a,b)
       if(len(a)==1 and  len(b)==1)
          append b to array at ath index in comparisonarray.
          append b to array at bth index comparisionarray.
          return max(a,b)
       else
          return max(findlargest(1stHalfof(a),2ndHalfof(a)),findlargest(1stHalfof(b),2ndHalfof(b))

    input= input_array()
    largest=findlargest(1stHalfof(input),2ndHalfof(input))
    subarray=[array at index largest in comparisionarray]
    2ndlargest=findlargest(1stHalfof(subarray),2ndHalfof(subarray))
    print(2ndlargest)
</code>```

Edit:  It can be done in minimum n+logn−2 comparisons. That is the only condition . This answer on math.stackexchange.com proves it. It has been generalized for nth largest element

Seems that there is a solution at this link stackoverflow. But i am not sure about the extra space and time complexity.

Body:
It looks like you're trying to do some sort of divide-and-conquer that you might find in a sorting algorithm.  Sorting and taking the second value from the large end would work, but it's overkill for this problem because you don't really need to have the set of elements sorted when you're done.

The brute-force solution is O(n-1), does at most 2*(n-1) comparisons and occupies space equivalent to two of your set members:

l1 := first_member_in_set  -- Largest value
l2 := first_member_in_set  -- Second-largest value

for each set member m after the first
    if m > l1
        l2 := l1
        l1 := m
    else if m > l2
        l2 := m
    end if
end for

Note that for this to work (and for there to be a second-largest member at all), the set must have at least two members.


答:
Parsing is inherently complex.  It's difficult to do correctly, and even more difficult to do elegantly.  A lot of code is not necessarily a sign of a problem.  However, there are a lot of things you can do to make it easier.

Use functions instead of cramming everything into your yacc file.  You want a yacc file to be only the specification of your grammar, putting as much implementation as possible into other files.  This lets you debug the grammar more easily, and also helps you recognize redundancy more easily.

Spend a lot of time getting your grammar right before you work on implementation.  I didn't look at your file in depth, and my yacc is a little rusty, but it seems there is a lot of repetition that could be eliminated with a better grammar.  Adding extra non-terminals in certain places can save you a lot of work.  In particular, instead of listing all possible combinations of vector, scalar, and matrix expressions separately, try combining them into one non-terminal called a value or something, combine your operators into one non-terminal called op or something (or group based on operator precedence), and write rules like value op value.

You're putting a lot of semantics into your parser, where you should focus mainly on structure, and implement the semantics in other files.  Try making the output of your parser just an AST.  Simple parsers, like the kind you find in tutorials, can skip this step, but you'll find for moderately complex languages you really need that extra layer.

Title: How do I simplify a compiler/interpreter?

Body:
Recently I wrote an interpreter for operations on sparse matrices (a "sparse matrix calculator") in lex/yacc.  The language is still very bare bones and doesn't even include control structures or parameterized subroutines, yet it is already at several thousand lines of code, and that's not including the matrix classes.  In particular, the yacc file is close to two thousand lines in length.  Because of this I'm finding it quite difficult to work on.  Is this normal or is there a way I can simplify things?

If you want to review my code, it can be found at:
http://sourceforge.net/projects/msci/files/libpetey/


问:
Object-Oriented Object Transformations
At my company, we are considering rewriting our business logic and database to have a better architecture after years of organic and unforeseen growth, leading to the inevitable maintenance nightmare.

The business model is one where a, let's say, cookie flows through multiple steps, changing states along the way. It is received raw, gets cooked, and is potentially split into two or more smaller cookies depending on the order. At this point, one of two things could happen: one, the cookie or cookies are considered finished and sent out to the customer, or two, the cookies requires outside processing (adding icing, adding food coloring, cutting to a design (there is no theoretical limit to an outside processing change to a cookie but it always changes the physical properties)), from which it is sent straight to the customer or back to us for shipment. The customer can reject the cookies if they don't find them to their standards, and we can then store and attempt to resell the cookies to a less discerning customer and/or send them to outside processing again as per the customer's whim.

The way our system currently works is initially assigning it a Raw Cookie number, then baking and/or cutting it and assigning the resulting cookie(s) a Finished Cookie number, one for each cookie. However, there is no common ground between any types of Cookies, resulting in a lot of extra code.

I'm trying to propose an object-oriented approach. I am fresh out of college while my coworkers are close to 30 or more years older than me; they know little about it and some are hesitant to change, so my model has to be pretty solid. I have worked with it academically, but never practically, and especially not when monitoring the form of a flow of a specific object. I may be a bit off in my understanding, but I believe OO is the best choice for this problem.

I have a UML diagram showing my proposed class hierarchy. Each kind of cookie that can be instantiated has access to a function that turns it into the next step's cookie. Is this a correct way of doing it? Would it be better to have these toCookie() functions accessed through the static abstract Cookie class?

Don't worry too much about inherited method placement, I'm just trying to understand how objects transform here.

答:
Generally I would not burden the cookies with responsibilities for managing their subsequent state (in your own words: "a function that turns it into the next step's cookie").

Instead split the design into:

business objects (cookies of different types)

these would be passive data containers, e.g. something to store in DB

business process steps (cookie factories to transform cookies)

A RawCookieFactory that creates raw cookies from thin air

A FinalCookieFactory that creates one (or more) final cookies fron a raw cookie

An OutSideCookieProcessor adding embellishments to a final cookie

etc.

business process controller (at least one ...)

There should be plenty of frameworks available to implement something like that (depending on implementation language, etc.) ...

Title: Object-Oriented Object Transformations


问:
What's so bad about creative coding?
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.

答:
There's nothing wrong with code-test-refactor-repeat, just tell people you're prototyping.

On the other hand, for larger projects you will find that some thought given to the design up-front will save you a lot of time in the oh-crap-now-what loop!

P.S.: Diagramming techniques help you to learn visual thinking skills, which are valuable even if no one but you ever sees your diagrams.

Title: What's so bad about creative coding?


问:
Should shopping carts be secure via SSL/TLS
So, pretty straight forward question. Somebody told me that all shopping carts should be secure. I can see in some instances where this would be beneficial... but all instances?

I realize that typically carts are stored on the server via a session, but in the end the details of the cart have to be sent to the user so they can see what is in their cart.

This is very difficult to google because all that comes up is ads for commercial shopping carts.

Question: Is it a standard/typical to secure all shopping carts? (pages which display the shopping cart)

答:
It depends on which stage you're talking about.

The paying for the contents of a shopping cart? This must be secure; you've probably got financial data involved (or something very similar). Failure to secure this will get you into trouble in virtually all jurisdictions.

The configuring of where to deliver to? It's a very good idea to make this be secure; it's definitely likely to be personally-identifiable information. Failure to secure this will get you into trouble in some jurisdictions; others are less bothered by it.

The adding of items to the cart, viewing of the current cart contents, or the removal of now-unwanted items? Strictly need not be secure, assuming there's a confirmation step later during the check-out stage, but having someone else pranking things by adding or removing random items from your customers' carts would still be rather undesirable. Can you imagine the effect on the opinion of a user of your site if some script kiddie decided to add a hundred pairs of expensive frilly lace underwear to every order, just for laughs? (OK, that might be OK with some customers, but they'll likely be a small minority.)

The cost of securing the cart completely isn't too large given that you already need to think in terms of secure operations for part of the process. With modern computing and network capabilities making the additional technical overburden quite limited, you might as well secure fully.


答:
The simple answer is yes. You already need encryption when communicating passwords or payment details, so it's easy to extend the encryption to the whole site. This might even simplify some things. Yes, serving encrypted pages is more computationally intensive than serving plain files, but we've come to generally expect HTTPS everywhere (especially post 2013).

The more nuanced answer is that few actions really have to be secured, namely the communication of secrets like passwords or payment details, and the final, legally binding purchase action when checking out the shopping cart. Generally, the items in the shopping cart (or adding items to the cart) wouldn't have to be protected, but this plays fast and loose with the users trust.

There also may be legal requirements on securing user's data which may mandate an encryption on the connection.

Title: Should shopping carts be secure via SSL/TLS

Body:
So, pretty straight forward question. Somebody told me that all shopping carts should be secure. I can see in some instances where this would be beneficial... but all instances?

I realize that typically carts are stored on the server via a session, but in the end the details of the cart have to be sent to the user so they can see what is in their cart.

This is very difficult to google because all that comes up is ads for commercial shopping carts.

Question: Is it a standard/typical to secure all shopping carts? (pages which display the shopping cart)


答:
I'm much the same way.  Listen when other people tell you about things that worked for them, but ignore anyone who tells you what you "should" be doing as though there were some moral imperative to it.  If you find something that works for you, go with it.  I mean, the end result is what's important isn't it?  Who really cares about the path you took to get there?

Remember:  people are different.  That's a good thing.  Don't listen to people who try to make you like them, and resist the urge to make other people like you and you'll do fine.

Title: What's so bad about creative coding?

Body:
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.


问:
Should methods returning a hashmap of string to object be avoided?
In my current code I have felt the desire multuple times to have helper methods that generate a collection of objects and return them as a map of string to object, with the string being some unique id like the objects label.  Many of my objects have gaurenteed unique labels since these labels are used via restful interface when querying the object.

The reason I want to do this is efficency.  I may have a decent sized collection and I know that the method calling whatever private helper method I wrote will definately want to search for specific objects within my collection, so returning them as a map allows the calling method to run in O(n) instead of O(n^2).

However, I feel that the return is not self documenting.  The key is just a string, there is nothing that makes it obvious that the string is specifically the objects label.  Obviously I will have comments to that effect, but ideally self documenting code is writen so well one doesn't have to go to method delarations to figure something out.

So I have a few questions:

1) Is the fact that i find myself needing to return maps a code-smell in itself? (other then possibly premature-optimization, which I know I may be a little guilty of, but I don't feel too bad about worrying about the big O of a method)

2) Is this generally acceptable, or should I be looking into a cleaner approch?  For instance should I have be making some map object that auto-maps any object by label?  What about places that I want to return a map where the key is a different key, should I make a wrapping object for all of them?  or is my map good enough?

EDIT:

More detail was asked, so to clarify my specific situation.  I am working within java.  While I may have unique strings they aren't known until compile time and enums are not a good fit, or I would have used them!  I'm not using reflection or any other systems to dynamically generate data, the methods and their meaning is pretty much standard each time.  Usually using the equivalent of a UUID of the objects (which in this case is a string which is used throughout the domain), or the label, which is a guaranteed unique string used to reference the object in question for a restful call.

答:
The decision depends on many things:

Is the caller method aware(at code-time) of the map's structure?

When I say "code-time" I mean that when you write the code you have a specific structure in mind(compared to compile-time and runtime). If you don't, and the method should be able to handle any structure you throw at it(for example - a method for converting that map to JSON format), then you don't really need to document that structure outside the method that creates the map, since it doesn't need to be refered by a human outside the scope of that method.

Are you using a static or a dynamic typed language?

Dynamic languages tend to depend less on well defined data structures. In JavaScript, for example, there is no difference between an object and a map, and Ruby has OpenStruct that creates objects that are both structs and maps. When you don't have a strong type system you should be less strict about writing self-documenting code at the API level.

Does the language you use provide a better way to do what you want?

For example, many static typed languages have enum types, and you can often use those enum types as the keys of a map instead of string. This will allow you to have the self documenting code you want(the enum type declaration is a list of all keys used in that map) while still being able to iterate over all the key-value pairs without using reflection.

If you provide more details we might be able to provide more help.