问:
At what volume is a specific data structure considered useful
I had this discussion with co-workers before. We had to store users by id and we'd do mostly Add/Get operations on it. I proposed to use a Dictionary which seems like the logical choice. My co-worker argued that the Dictionary was pointless in that case because we didn't have many users (Maybe 150).

I proposed the dictionary because I know, in theory, that it's the best data structure for this scenario. In the case where I have 150 users (that's an arbitrary number), is there really a performance difference between the O(1) access of a Dictionary and the O(n) access of a List?

He proposed the List because the Dictionary seemed useless in that case.

We ended up using the Dictionary because if the application was to grow, we'd have more users and the Dictionary would prove useful.

Though the question remained, are there scenarios where we shouldn't consider which data structures to use?

答:
In this case, a dictionary is more appropriate but there are really two considerations here:

How do you identify the data?

How do you add or remove the data?

A list accesses by index. This is simply the ordering of the elements in the data structure. A dictionary or hash table adds another layer by using a key, and its hash is the index into the underlying array.

In your case you need a structure where you can use user IDs to access the data. What would you rather do?

This:

```<code>dictionary.get(userId);
</code>```

Or this:

```<code>for (User u : users) {
  if (userId == u.userId) {
    return u;
  }
}
</code>```

It makes more sense to get a user by ID rather than searching the whole list (it is O(n)) for it.

The other consideration is how you add or remove data. This goes back to the whole "array list v linked list" discussion that is taught in any undergraduate CS program so I will omit that here. The other detail to keep in mind is that it is appropriate for dictionaries, too: you can implement them with an array (hash table) or a tree. Each has benefits and drawbacks and is more efficient at different types of mutations and accesses.

Note that at no time does "how much data will there be" enter into the equation. Typically, the above concerns drive the data structure selection, not the quantity of data. The only time this should be an issue is if there is so much data it cannot all fit into memory at once.

Body:
In this case, a dictionary is more appropriate but there are really two considerations here:

How do you identify the data?

How do you add or remove the data?

A list accesses by index. This is simply the ordering of the elements in the data structure. A dictionary or hash table adds another layer by using a key, and its hash is the index into the underlying array.

In your case you need a structure where you can use user IDs to access the data. What would you rather do?

This:

dictionary.get(userId);

Or this:

for (User u : users) {
  if (userId == u.userId) {
    return u;
  }
}

It makes more sense to get a user by ID rather than searching the whole list (it is O(n)) for it.

The other consideration is how you add or remove data. This goes back to the whole "array list v linked list" discussion that is taught in any undergraduate CS program so I will omit that here. The other detail to keep in mind is that it is appropriate for dictionaries, too: you can implement them with an array (hash table) or a tree. Each has benefits and drawbacks and is more efficient at different types of mutations and accesses.

Note that at no time does "how much data will there be" enter into the equation. Typically, the above concerns drive the data structure selection, not the quantity of data. The only time this should be an issue is if there is so much data it cannot all fit into memory at once.


问:
Should Write-Debug statements be left in production PowerShell code?
This is one of my functions I have in a module:

```<code>Function Get-DatabaseUser
{
    [CmdletBinding()]
    Param()
    Write-Verbose 'Getting database...'
    $Database = Get-Database
    Write-Debug('Value of $Database: {0}' -f $Database)

    if($Database -eq $null)
    {
        $ErrorRecord = New-ErrorRecord "Database could not be accessed." NullReferenceException 'DatabaseInaccessible' ObjectNotFound
        $PSCmdlet.ThrowTerminatingError($ErrorRecord)
    }

    Write-Verbose 'Refreshing user list...'
    $Database.Users.Refresh()

    Write-Verbose 'Getting user list...'
    $Users = $Database.Users |
                       Where-Object { $_.LoginType -eq 'WindowsUser' } |
                       Select-Object -Property Name, Login

    Write-Debug("Number of users: {0}" -f $Users.Count)

    Write-Verbose 'Writing user list to output...'
    Write-Output($Users)
}
</code>```

Is there any reason to keep the Write-Debug statements in my production code, or could these statements be replaced with Write-Verbose? For example, replacing

```<code>Write-Debug("Number of users: {0}" -f $Users.Count)
</code>```

with

```<code>Write-Verbose '3 users found.'
</code>```

I'm not sure about the internals of PowerShell and if Write-Debug generates any significant overhead, but I'm still wondering if this has any place in a script used in production or purely for debug versions of my scripts/modules.

答:
I cannot imagine that Write-Debug adds any significant overhead to a PowerShell script.  Even if it did does it matter?  I do not typically write scripts for performance critical operations - usually I am just trying to automate some mundane task that I am tired of doing manually.  It is not going to be the end of the world if I do not squeeze every last ounce of performance out of one of my scripts.

Personally, I leave all my Write-Debug statements in my production scripts.  The information that I report with Write-Debug tends to be of a different nature than the information I report with Write-Verbose so I would not want to mash the two together.

ContentLicense: CC BY-SA 3.0


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: Choose fast editor, fast compiler, and write software with fast execution time. This way you can make ten times as many mistakes as normal programmer and still become better than others. That's probably one the reasons google applications are so popular. Web development is filled with nasty bugs, and writing more software on buggy platform is pain the ass. But the response time between editing code and seeing outcome is so fast that it's still easier to make that mountain of garbage work than extending c++ programs. :)</p>

OwnerDisplayName: Nick Gotch

ContentLicense: CC BY-SA 2.5

Title: How to become a "faster" programmer?

OwnerDisplayName: AareP


答:
Your coworker have a strange logic. A dictionary might not have a performance-benefit if the number of items is small, but that does not mean that there is any benefit to using a list instead!

If the number of operations is small then the performance difference is probably unimportant either way, so you should choose the data structure which is simplest to work with for the task at hand. If you want to store users by id, a dictionary seem like the natural choice.

Title: At what volume is a specific data structure considered useful

Body:
I had this discussion with co-workers before. We had to store users by id and we'd do mostly Add/Get operations on it. I proposed to use a Dictionary which seems like the logical choice. My co-worker argued that the Dictionary was pointless in that case because we didn't have many users (Maybe 150).

I proposed the dictionary because I know, in theory, that it's the best data structure for this scenario. In the case where I have 150 users (that's an arbitrary number), is there really a performance difference between the O(1) access of a Dictionary and the O(n) access of a List?

He proposed the List because the Dictionary seemed useless in that case.

We ended up using the Dictionary because if the application was to grow, we'd have more users and the Dictionary would prove useful.

Though the question remained, are there scenarios where we shouldn't consider which data structures to use?


问:
Setting up my inheritance model?
I'm working on refactoring a synchronization web app that our company uses. Currently it's merely a set of controllers that fire up a set of helpers that go through a long chain of if-else type statements.

I'm attempting to build a wrapper around the SalesForce Soap web reference, but I'm having some trouble coming up with a good inheritance model.

When using the wrapper, I want to essentially be able to say something like

```<code>var SalesForce = new SalesForceApi(Username, Password, Url);
var tmp1 = SalesForce.Users.GetUsers();
// or
var tmp2 = SalesForce.Users.GetUserById(id);
// or
var tmp3 = SalesForce.Organizations.GetOrganizations();
// you get the picture.
</code>```

Ideally I would want to instantiate the SalesForceApi object, and simply pass its active connection through all of it's different requests and request types. I'm just a bit fuzzy on the implementation portion.

I think I'm somewhat getting into the right direction.

I created an Abstract class called Base that contains an object called Binding with the type SforceService. It contains login and logout methods that are used to create an active connection. When a SalesForceApi object is created with the username, password, and url, these are passed to the sub classes like Users which inherit the Base class. These values are then passed to the Base class to create an active binding object.

Edit

Here are a few classes I built that give me somewhat of a method of accomplishing what I want.

My Main SalesForce class (or SalesForceApi)

```<code>namespace SyncTool.Core.Services.SalesForce
{
    public interface ISalesForce
    {
        IAccounts Accounts { get; }
        IAttachments Attachments { get; }
        ICases Cases { get; }
        IContacts Contacts { get; }
        IGroups Groups { get; }
        IRecordTypes RecordTypes { get; }
        IUsers Users { get; }
    }

    public class SalesForceApi:ISalesForce
    {
        public IAccounts Accounts { get; set; }
        public IAttachments Attachments { get; set; }
        public ICases Cases { get; set; }
        public IContacts Contacts { get; set; }
        public IGroups Groups { get; set; }
        public IRecordTypes RecordTypes { get; set; }
        public IUsers Users { get; set; }

        public SalesForceApi()
        {
            Accounts = new Accounts();
            Attachments = new Attachments();
            Cases = new Cases();
            Contacts = new Contacts();
            Groups = new Groups();
            RecordTypes = new RecordTypes();
            Users = new Users();
        }
    }
}
</code>```

The Request Base class

```<code>namespace SyncTool.Core.Services.SalesForce.Requests
{
    public abstract class RequestBase: IDisposable
    {
        private const string User = "foo@bar.com";
        private const string Pass = "foobar";
        private const string Url = "url";

        public SforceService Binding;
        public Logger Logger = LogManager.GetCurrentClassLogger();

        protected RequestBase()
        {
            Login(User, Pass, Url);
        }

        public bool Login(string username, string password, string url)
        {
            Binding = new SforceService { Url = url, Timeout = 60000 };
            LoginResult lr;

            try
            {
                lr = Binding.login(username, password);
            }
            catch (SoapException e)
            {
                Logger.Error("An error has occurred",e);
                return false;
            }

            Binding.SessionHeaderValue = new SessionHeader { sessionId = lr.sessionId };
            Binding.Url = lr.serverUrl;
            return true;
        }

        public bool Logout()
        {
            try
            {
                Binding.logout();
                return true;
            }
            catch (SoapException)
            {
                return false;
            }
        }

        public void Dispose()
        {
            Logout();
            Binding.Dispose();
        }
    }
}
</code>```

And here's an example of one of the request classes

```<code>namespace SyncTool.Core.Services.SalesForce.Requests
{
    public interface IUsers
    {
        List<User> GetUsers();
        User GetUserById(string id);
        List<User> GetUsersByEmail(string email);
        User GetUserByEmail(string email);
    }

    public class Users : RequestBase, IUsers
    {
        public List<User> GetUsers()
        {
            try
            {
                const string soqlQuery = "SELECT Id, Name, FirstName, LastName, Email FROM User";
                var qResult = Binding.query(soqlQuery);
                var done = false;
                if (qResult.size <= 0) return new List<User>();
                var users = new List<User>();
                while (!done)
                {
                    var records = (qResult.records.Cast<User>().ToList());
                    users.AddRange(records);
                    if (qResult.done)
                        done = true;
                    else
                        qResult = Binding.queryMore(qResult.queryLocator);
                }
                return users;
            }
            catch (SoapException e)
            {
                Logger.ErrorException("An unexpected error occurred when retreiving users.",e);
                return null;
            }
        }

        public User GetUserById(string id)
        {
            try
            {
                var qResult = Binding.query("SELECT Id, Name, FirstName, LastName, Email FROM User WHERE Id='" + id + "'");
                if (qResult.size <= 0) return new User();
                var records = (qResult.records.Cast<User>().ToList());

                return records.Count > 0 ? records.FirstOrDefault() : new User();
            }
            catch (SoapException e)
            {
                Logger.ErrorException("An unexpected error occurred when retreiving users.", e);
                return null;
            }
        }

        public List<User> GetUsersByEmail(string email)
        {
            try
            {
                var qResult = Binding.query("SELECT Id, Name, FirstName, LastName, Email FROM User WHERE Email='" + email + "'");
                if (qResult.size <= 0) return new List<User>();
                var records = (qResult.records.Cast<User>().ToList());

                return records;
            }
            catch (SoapException e)
            {
                Logger.ErrorException("An unexpected error occurred when retreiving users.", e);
                return null;
            }
        }

        public User GetUserByEmail(string email)
        {
            try
            {
                var qResult = Binding.query("SELECT Id, Name, FirstName, LastName, Email FROM User WHERE Email='" + email + "'");
                if (qResult.size <= 0) return new User();
                var records = (qResult.records.Cast<User>().ToList());

                return records.Count > 0 ? records.FirstOrDefault() : new User();
            }
            catch (SoapException e)
            {
                Logger.ErrorException("An unexpected error occurred when retreiving users.", e);
                return null;
            }
        }
    }
}
</code>```

答:
I'm attempting to build a wrapper around the SalesForce Soap web reference

I don't see anything in what you show that gets to wrapping a SOAP thingy.  But please bear with me as I go through what I see...

When using the wrapper, I want to essentially be able to say something like ...

I call this "wishful thinking design." Design things they way you want them to be. Then wrap or manipulate the existing target object so we can use it the way we want to.

Sketch out classes that support what you want. So far I see:

SalseForceApi class, containing

Users collection

Organizations collection

UserName, Password, URL

No idea yet if these are separate properties or contained w/in 1 or more other classes

SforceService object

User class

User collection class

GetUserById

GetUsers

Organization class

Organization collection class

GetOrganizations

SforceService class

Login

Logout

Base (abstract class)

very bad name.

... Users which inherit the Base class.

This seems to be just one more issue in the overall design but you seem to be saying "inheritance model" is the central issue. This seems to suggest that the User contains a wrapped SOAP reference object.

I'm not seeing inheritance as the solution. Granted I'm profoundly ignorant of your problem space, but ignorance is bliss. So here we go...

sForceService

I see this as the wrapper you talk about. And we're basically talking about the adapter pattern idea here.

The wrapper encapsulates all the grunt work of creating and using the soap object. It exposes what the soap object contains.

'SalesForceApi' passes along that stuff through the "Sales Force API".

Composing the Adapter

```<code>public class sForceService {
    public sForceService ( User theUser, ??? url ) {
         // in here set up with stuff provided by theUser
   }

   // the adapter makes the connection, fetches stuff and exposes same
   // through public methods...
}

public class SalesForceApi {
    protected sForceService SFS { get; set; }

    // Maybe the api class constructor, in part, might looks a little like this
    public SalseForceApi ( string userName, string password, ??? url ) {
        User someOne = new User(userName, password);
        sForceService SFS = new sForceService ( someOne, url);
    }

    public User User(int id) {
        return SFS.User(id);
    }

    public UserCollection Users {
        get { return SFS.Users(); }
    }

    public OrganizationCollection Organizations {
        { get SFS.Organizations(); }
    }

    public OrganizationCollection UserOrganizations (User forThisGuy) { }
}

//CLIENT code
SalesForceApi sfa = new SalesForceApi ( someUser, someURL );
var tmp1 = sfa.User(34);
var tmp2 = sfa.Users;
var tmp3 = sfa.Organizations;
var tmp4 = sfa.UserOrganizations( fred );
</code>```

Title: Setting up my inheritance model?

Body:
I'm attempting to build a wrapper around the SalesForce Soap web reference

I don't see anything in what you show that gets to wrapping a SOAP thingy.  But please bear with me as I go through what I see...

When using the wrapper, I want to essentially be able to say something like ...

I call this "wishful thinking design." Design things they way you want them to be. Then wrap or manipulate the existing target object so we can use it the way we want to.

Sketch out classes that support what you want. So far I see:

SalseForceApi class, containing

Users collection

Organizations collection

UserName, Password, URL

No idea yet if these are separate properties or contained w/in 1 or more other classes

SforceService object

User class

User collection class

GetUserById

GetUsers

Organization class

Organization collection class

GetOrganizations

SforceService class

Login

Logout

Base (abstract class)

very bad name.

... Users which inherit the Base class.

This seems to be just one more issue in the overall design but you seem to be saying "inheritance model" is the central issue. This seems to suggest that the User contains a wrapped SOAP reference object.

I'm not seeing inheritance as the solution. Granted I'm profoundly ignorant of your problem space, but ignorance is bliss. So here we go...

sForceService

I see this as the wrapper you talk about. And we're basically talking about the adapter pattern idea here.

The wrapper encapsulates all the grunt work of creating and using the soap object. It exposes what the soap object contains.

'SalesForceApi' passes along that stuff through the "Sales Force API".

Composing the Adapter

public class sForceService {
    public sForceService ( User theUser, ??? url ) {
         // in here set up with stuff provided by theUser
   }

   // the adapter makes the connection, fetches stuff and exposes same
   // through public methods...
}

public class SalesForceApi {
    protected sForceService SFS { get; set; }

    // Maybe the api class constructor, in part, might looks a little like this
    public SalseForceApi ( string userName, string password, ??? url ) {
        User someOne = new User(userName, password);
        sForceService SFS = new sForceService ( someOne, url);
    }

    public User User(int id) {
        return SFS.User(id);
    }

    public UserCollection Users {
        get { return SFS.Users(); }
    }

    public OrganizationCollection Organizations {
        { get SFS.Organizations(); }
    }

    public OrganizationCollection UserOrganizations (User forThisGuy) { }
}

//CLIENT code
SalesForceApi sfa = new SalesForceApi ( someUser, someURL );
var tmp1 = sfa.User(34);
var tmp2 = sfa.Users;
var tmp3 = sfa.Organizations;
var tmp4 = sfa.UserOrganizations( fred );


答: Spend more time putting things together in your mind than in front of the IDE. When you have a plan, you already have most of the work already done. Implementing is just the other 20%. If you get stuck while writing code due to platform-specific problems, stick to the plan, and keep on implementing and testing the rest. In the end, tackle all the spots you've left behind, solving them one by one - it's possible that some will be related, and solving a few might be enough to figure out the rest. I usually use workarounds for such problems, adding "//TO CHANGE" comments at the particular places in code, and rewrite the ones that have the most impact on quality and performance in the end, if I don't have time to resolve all of them by the deadline.</p>

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: luvieere


问:
Data Layer vs Business Layer
I think I'm in the minority on this but would be curious to see other perspectives.

A lot of times I see people talk about the Data Layer like having functions like UpdateCustomer() or Summarize(). I really feel like the Data Layer should be more abstract than that. I currently use a generic Repository pattern on top of entity framework in my data layer. So I get functions like Find(int id), Update(), Save(), All(), etc. Very generic functions.

Then I make Business Logic layers that have more specific functions like Summarize() that work on the generic Data Layer. For me just isolating the data access technology is enough for the Data Layer. That's a big enough job on it's own. Why provide these seemingly query functions in your Data Layer? The business logic I write a large part of the time is inside Linq queries themselves so for me all specific queries should be in the Business Layer and not the Data Layer, but this isn't what I often see.

On top of that, because my Data Layers are not very generic, I can share them, they are DLL's, with other Business Layers (often web services) so that I can combine very different pieces of data together in a Business Layer to join queries between the 2 (since I have generic access to the underlying data) and it also helps in not having to recreate Data Layers for each separate solution. To me it's great resuabiltiy.

I'm wondering what the opposite view is on my view here. Why am I "wrong" in thinking this way and why is the other way "right"?

答:
It's a matter of definition of the terms Data and Business. Your perspective seems to be that the Data Layer is dealing with data generically and the Business Layer tells the Data Layer which data.

Another perspective is to consider the Data Layer as consisting of the collection/attributes of data classes and the Business Layer as consisting of the methods of data classes.

The only con I can think of with your approach is that the Business Layer can get a bit heavy.

Title: Data Layer vs Business Layer


问:
Is it an overkill to write unit tests for a small code base?
I am the sole maintainer of a code base of about 2000 lines of code. It's not big, but over time the code became so unmaintainable my boss agreed to give me time to rewrite it from scratch.

Since the code became such a nightmare to maintain and extend, I wanted to do things right this time and thought about writing unit tests from day 1 (the current code has no tests). However I'm uncertain about this.

On one hand, I estimate the code base will probably never exceed 2000 or 1500 lines of code in size. On the other hand, this app is estimated to be in use for a while, I assume at least for 6 months.

So the question is: What size of code base justifies writing unit tests? Is unit testing overkill for a project of this size? Or do the reasons to write unit tests for larger projects apply here as well?

Please note that I am aware of the great advantages of having unit test coverage of the code base. I'm simply wondering whether this would be an overkill for such a small app.

答:
We do unit tests to ensure (*) the correctness of code.

(*) to ensure: in a colloquial, not mathematical sense.

The question of correctness of code applies regardless of whether you have 5 lines of code, 2000 lines of code, or 200000 lines of code.

I mean, a binary search routine is 10 lines. You would be insane to not unit-test it.

So, the choice is yours.  (So to speak.)

If we are to take "small codebase" to mean "correctness is unimportant", then sure, don't test anything.  But there is nothing that equates the two.

If correctness is of importance, then it is advisable to test at least those portions that are crucial for the correctness of the application and that are hard to test by simply running the application. And there will always be those.
(More discussion about that in the comments below.)


答: Use an ergonomically optimized keyboard layout. Some are even aimed at programmers, through very accessible special chars.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: knittl


答:
Before you think about unit testing, you need to look into why the code is a "nightmare to maintain and extend".

It is very possible that there are a lot of undocumented changes in it, therefore causing difficulty.  You MUST absolutely be 100% certain that your rewrite will not ignore currently implemented, but undocumented, patches to this code.  Your unit test will be 100% useless until you figure out exactly what your code need to do.

Also, try this article regarding software rewrites.

Now specifically about the question "What size of a codebase 'justifies' writing unit tests?"  There is never overkill for unit tests, as other answers have tested.

Even regular expressions, usually only a single line, requires unit tests.  My unit tests for my regular expressions are at minimum 10 distinct inputs, and then some more time is spent to specifically break them.

Title: Is it an overkill to write unit tests for a small code base?

Body:
I am the sole maintainer of a code base of about 2000 lines of code. It's not big, but over time the code became so unmaintainable my boss agreed to give me time to rewrite it from scratch.

Since the code became such a nightmare to maintain and extend, I wanted to do things right this time and thought about writing unit tests from day 1 (the current code has no tests). However I'm uncertain about this.

On one hand, I estimate the code base will probably never exceed 2000 or 1500 lines of code in size. On the other hand, this app is estimated to be in use for a while, I assume at least for 6 months.

So the question is: What size of code base justifies writing unit tests? Is unit testing overkill for a project of this size? Or do the reasons to write unit tests for larger projects apply here as well?

Please note that I am aware of the great advantages of having unit test coverage of the code base. I'm simply wondering whether this would be an overkill for such a small app.


答:
Is it overkill to write tests for a small code base?

Absolutely not.

Code bases have a way of growing on us. You've seen this play out first hand already. What was a few hundred LoC grew into a few thousand. A few thousand can easily grow into tens of thousands.

Have you ever heard of the broken window theory? If you start with tests, it's more likely that more tests will be written as functionality is expanded and bugs are fixed. If they're not there, people are unlikely to write them later (not to mention that they'll be harder to write later and won't cover as many cases).

So, yes, write the tests, but I'd urge you to reconsider completely rewriting the code from scratch. You'd do much better to pick yourself up a copy of Michael Feather's Working Effectively with Legacy Code and putting it under tests before and while you're making changes to it. It's a small project, but that doesn't mean that it can't/won't suffer the same fate as Netscape.


答:
Every significant decision in engineering, or business in general, or life in general, can stand to gain from a COST-BENEFIT ANALYSIS.  The secret to success is achieving maximal efficiency; we all have limited resources and don't want to compromise quality.  "Develop tests for only that which will benefit from them."  As professionals, we get paid to make value-creating judgment calls like that.

There are no simple formulas.  A 10-line function that does cryptic math calculations will probably benefit from a unit test.  A 1,000-line set of formatted output statements probably won't.

The same holds true for the number of tests per unit.  Some units may benefit from 40 different test cases.  Others may benefit from no more than 4.

Think of taking a standardized exam.  Does it make sense to check all your answers twice, 3 times, more?  If you finish the exam in an hour but are allotted 4 hours, is it worth it to you to check each of your answers 8 times?  How many errors would you expect to catch in an 8th round of checking?  At some point, you call it a day and turn in your exam.


答:
A bit lengthy of a post here, but the whole testing thing has been giving me an itch lately...

It really depends on the nature of the code. Testing as religion is absolutely stupid. Never testing code that is 90% pure, side-effect free, well-bounded functions is equally stupid. Never writing tests as an exercise to help you understand what the bounds of a pure function should be can leave your code in a state of limbo where you don't really understand what it does, how it should be structured, or where the corners are.

The third case is the real reason I write tests on old code. We already know it works well enough, but until I mess around with it I will never fully grok it, yet I am the maintainer. See the problem? Testing is an opportunity in this case. It forces me to understand it, and understanding it allows me to see where I can factor out side effects, create pure functions that truly are testable, and transform the code into something inherently testable, well-bounded, and full of explicit semantic meaning the next maintainer will grok immediately.

Why would you not do that? (A: Because the world is on fire, the company is in the red and you have bigger fish to fry just then... (note that this can also be a reason for doing tests))

But I'm not talking about writing tests for testing's sake -- that is a fad gripping the industry right now, replete with buzzwords, consultancies, methodologies based entirely around it, etc. And yet software still has, well, just as many bugs as it used to.

To quote from Rich Hickey:

What does every bug in the wild have in common?
  They passed all the tests.

That joke is on us.

But these words: "pure", "testable", "bounded"... what do they mean?

When I talk about pure, testable, bounded functions, I mean functions that do not depend on any external resources or shared mutable state and provide a return value that we can test. No file descriptors are being passed around, no socket of indeterminate state is coming in or out, we're not trying to get control of a camera or GPS device that may or may not exist, and we're (hopefully!) not dealing with a variable a or b that is referenced by other concurrent threads without being locked which might change randomly in the middle of the operation.

With a function that has an input and an output, we can write a test and actually know something about it. Writing a test for an entire object, on the other hand, becomes somewhat more problematic -- especially in a concurrent system. Several threads may be referencing that object at the same time, internal state that the return value of a method call depends upon may change unexpectedly halfway through execution unless the relevant memory locations are locked -- and if they are not released other problems occur.

Managing the complexity of the interactions among threads can be a real mess and renders quite a bit of OOP unit test code useless because method calls that update internal state were never made reentrant, and often places where a serialized communication scheme among threads is necessary are overlooked until the system has just crashed enough in production to "shake out the bugs".

In this environment an obsession with testing can turn a frustrating death march into an endless waking nightmare -- especially because in many cases the test environment influences the nature of the bugs present. That's when you get the fatal mix of "my testing environment suppresses bugs, so I can't find them", or, the even worse "the production environment works fine, but half the tests fail... wtf?" This problem is especially prevalent in short programs, because short programs usually exist for the express purpose of interacting with an external resource.

We forget that accessing external resources is another form of concurrency. Even in single-threaded code external system calls to do things like refresh the screen, get input device status, open a file, flush a network buffer, etc. are executed on their own schedule, sometimes independent of the executing thread (not all system calls block -- unless they do).

Instead of writing functions that open a file, check for some value in it, pass the file descriptor on to another function that appends it, then passes the file along to another function that does something else, collect the operations you want to do with that external resource in a single function, and call pure ones to get your values. (Protip: This is the magic that underlies the monadic movement in "pure fp". Its not as much about mathematical monads as formalizing a way of making batches of prayers to the system gods.)

It isn't always possible or practical to aggregate side effects for execution in a limited number of places, but refactoring with a clear goal of aggregating side effects can transform most of your codebase from a mysterious mess where you have 100% test coverage, but still >80% of the code's state is indeterminate at any given time. Flipping that around to where 10~20% of your code is where the side-effects happen, and the rest of the code doesn't touch the outside world leaves you in a much better situation.

Even on a tiny codebase this is can be a big win. ~2000 lines? Why wouldn't you do this? After all, silly bug was found in the canonical implementation of binary search after years of use.

On the other hand, a commitment to testing is, above all, a business decision. If you have a lot of stuff on your plate already, and those things are priority targets your organization needs to hit to satisfy some high priority goal and your tiny 2000 line program is working fine already -- then the testing can wait. The bug in binary search existed for about 30 years (and still does in most old code that is happily running in millions of systems across the world...) and yet nobody's hair has caught fire because of it.

As with so many other things in life, with testing you must seek balance.


答:
Nope, test the little ones, test the big ones - even test the ones you copy directly from the text book.

Joshua Bloch, who wrote the sort for java.util.Arrays, tracked down a bug which sat in one of the Java standard libraries for 9 years, and in a text book implementation for about 20 years.

It's very subtle, so likely affects a large portion of implementations of divide and conquer algorithms (at last as of 2006, it's a nice fantasy that this is probably no longer true).

Test everything you can.


问:
How many classes are too many?
I'm making a Book Manager App using Java Swing that allows me to do a variety of things such as opening a txt list of books, searching for books, adding/removing books.

There are different classes for the different types of books e.g. Fictional Books have their own genre field and history books have their own period field. All of these books extend an abstract book class which holds the base fields for these classes.

I'm using the MVC pattern and I'm happy enough with the model but my main concern lies with the view.

I currently have 22 classes with 14 of them focused on the View aspect of the model. I basically have classes for the majority of the components. Such as a file chooser which extends JFileChooser, a MenuBar class and classes for the different book panels. Each Sub book panel extends from a general book Panel by taking all of its textfields and labels and appending their own.

I've also implemented the Builder design pattern that lets me create a range of components so far a I have 2 builder classes both implementing an interface one for textfields and one for labels.

My question is, is all of this a little over the top? Is it better to have everything crammed into the main class or is it better to have a lot of classes?

答:
The main reason to have classes in any code is to make that code easier to follow.  If you feel that by adding classes, the code becomes clearer and more descriptive and conceptually meaningful...then you're on the right track.  But if you feel that by adding classes, the code becomes more muddled, sprawling, or obtuse...then don't do it.

There is no simple formula; every application is different.  Only a human can make judgment calls like these.  Otherwise computer programs could write themselves.  :)

Title: How many classes are too many?


答:
Build your own code library

Every time you code a new feature try to keep it generic as possible, but not too generic. In the short term this will be a little slower, but in the long term as your code libary gets bigger, each new project will be completed faster as a lot of business applications have similar needs (not always) but close enough that a lot of code can be reused.

Title: How to become a "faster" programmer?

OwnerDisplayName: Darknight


问:
I understand what a stack pointer is - but what is it used for?
The stack pointer points to the top of the stack, which stores data on what we call a "LIFO" basis. To steal someone else's analogy, it's like a stack of dishes in which you put and take dishes at the top. The stack pointer, OTOH, points to the top "dish" of the stack. At least, that's true for x86.

But why does the computer/program "care" what the stack pointer's pointing to? In other words, what purpose does having the stack pointer and knowing where it points to serve?

An explanation understandable by C programmers would be appreciated.

答:
In simple terms, the program cares because it's using that data and needs to keep track of where to find it.

If you declare local variables in a function, the stack is where they are stored.  Also, if you call another function, the stack is where it stores the return address so it can get back to the function you were in when the one you called is finished and pick up where it left off.

Without the SP, structured programming as we know it would be essentially impossible.  (You could work around not having it, but it would pretty much require implementing your own version of it, so that's not much of a difference.)


问:
Best Possible Way To Write Unit Tests For HTTP Middleware
I am using this go library(https://github.com/abourget/goproxy) to create a custom proxy server app. The app is utilizing several middleware of the following form:

```<code>MyMiddlewarFunc(ctx *goproxy.ProxyCtx) goproxy.Next {
    if ctx.Req.Header.Get("If-None-Match") == "test"{
       //do something
    }
}
</code>```

Now, I am trying to write unit tests for these middleware functions. Here are two possible different approach I could came up with:

Write test functions to call these middlware with custom made 'goproxy.ProxyCtx' instnace and inserting required dummy data in that structure. This would look something like:

func TestMyMiddlewarFunc() {
    ctx = &goproxy.ProxyCtx{}
    ctx.Req.Header.Set("If-None-Match", "test")
    ctx.Req.Header.Set("If-Modified-Since", "test")
    MyMiddlewarFunc(ctx)
    //verify if changes are done according to logic
}

Pros: This approach seems to working for most of the cases, simple to write.
Cons: Has one problem: as the ctx data structure is from a third party, sometimes it would be difficult to know what kind of data need to set inside it to trigger/execute something properly. For example, inside a middleware, I have a call to 'ctx.DispatchResponseHandlers' method, but it throws runtime error, most possibly because of something not set properly while passing the instance.

Create a test http server, handle the middleware, and send a custom request that would trigger the mechanism inside the middleware and then verify the response/internal to see if the changes are there.

```<code> func TestMyMiddlewarFunc() {

 proxyServer := goproxy.NewProxyHttpServer()
 proxyServer.HandleFunc(MyMiddlewarFunc)
 s := httptest.NewServer(proxyServer)

 client := &http.Client{}

 req, _ := http.NewRequest("GET", s.URL+"/foo", nil)
 req.Header.Set("Origin", "foo")
 resp, err := client.Do(req)

 //verify resp
 }
</code>```

Pros: This second approach seems to handle the problem faced on the previous approach.
Cons:

Has little bit more overheads for setup.

As there are several different middleware and dependencies among them, it requires to make several different mock methods to handle those dependencies, which making it more complex structure.

Moreover, its kind of having integration test flavour, but though its actually suppose to be unit test.

So, I am curious to know which approach would you choose and why? Some details to support your choice would be great.

答:
Neither #1 nor #2 would give you unit tests, in my opinion. While there is no objective distinction between unit test and integration test, a test that covers some code you own and some code you don't own would probably be considered integration more often than not.

Since Go supports first-class functions, the simplest way to convert your example to support real unit tests would be to change this:

```<code>MyMiddlewarFunc(ctx *goproxy.ProxyCtx) goproxy.Next {
    if ctx.Req.Header.Get("If-None-Match") == "test"{
       //do something
    }
}
</code>```

to something more like this:

```<code>MyMiddlewarFunc(ctx *goproxy.ProxyCtx, doSomething func()) goproxy.Next {
    if ctx.Req.Header.Get("If-None-Match") == "test"{
       doSomething();
    }
}
</code>```

Now you can easily write a test on whatever function you pass in for doSomething that doesn't need to know anything about goproxy. That would probably be a real unit test (assuming doSomething() is fairly simple).

This isn't to say that the two types of integration tests you describe are undesirable. In fact, you should have some of them. But you should aim to have a lot more unit tests than integration tests, as unit tests tend to scale much better and be less brittle. As to whether your integration tests should be of type 1 or 2, I agree with Robert's comment: Use 1 when 1 works and 2 when 2 works.

Body:
Neither #1 nor #2 would give you unit tests, in my opinion. While there is no objective distinction between unit test and integration test, a test that covers some code you own and some code you don't own would probably be considered integration more often than not.

Since Go supports first-class functions, the simplest way to convert your example to support real unit tests would be to change this:

MyMiddlewarFunc(ctx *goproxy.ProxyCtx) goproxy.Next {
    if ctx.Req.Header.Get("If-None-Match") == "test"{
       //do something
    }
}

to something more like this:

MyMiddlewarFunc(ctx *goproxy.ProxyCtx, doSomething func()) goproxy.Next {
    if ctx.Req.Header.Get("If-None-Match") == "test"{
       doSomething();
    }
}

Now you can easily write a test on whatever function you pass in for doSomething that doesn't need to know anything about goproxy. That would probably be a real unit test (assuming doSomething() is fairly simple).

This isn't to say that the two types of integration tests you describe are undesirable. In fact, you should have some of them. But you should aim to have a lot more unit tests than integration tests, as unit tests tend to scale much better and be less brittle. As to whether your integration tests should be of type 1 or 2, I agree with Robert's comment: Use 1 when 1 works and 2 when 2 works.


答: Faster doesn't mean better. If you manage to be a faster and better programmer. It all comes down to balance. How long you can do that ? Thinking, patience and planning always pay off. Sometimes "fast" in developement world could bring worst results. </p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Ryuken


答:
For the processor stack in an x86 processor, the analogy  of a stack of dishes is really inaccurate.

For various reasons (mostly historical), the processor stack grows from the top of memory towards the bottom of memory, so a better analogy would be chain of chain links hanging from the ceiling. When pushing something onto the stack, a chain link gets added to the lowest link.

The stack pointer refers to the lowest link of the chain and is used by the processor to "see" where that lowest link is, so that links can be added or removed without having to travel the entire chain from the ceiling down.

In a sense, inside a x86 processor, the stack is upside down but normal stack-terminology sill gets used, so that lowest link gets referred to as being the top of the stack.

The chain links that I referred to above are actually memory cells in a computer and they get used to store local variables and some intermediate results of computations. Computer programs care where the top of the stack is (i.e. where that lowest link hangs), because the large majority of variables that a function needs to access exist close to where the stack pointer is referring to and fast access to them is desirable.

Title: I understand what a stack pointer is - but what is it used for?

Body:
The stack pointer points to the top of the stack, which stores data on what we call a "LIFO" basis. To steal someone else's analogy, it's like a stack of dishes in which you put and take dishes at the top. The stack pointer, OTOH, points to the top "dish" of the stack. At least, that's true for x86.

But why does the computer/program "care" what the stack pointer's pointing to? In other words, what purpose does having the stack pointer and knowing where it points to serve?

An explanation understandable by C programmers would be appreciated.


问:
Business logic in the models?
I use the repository pattern for data handling.

In my DAL folder i have IUserRepository, UserRepository and UserContext. Inside the models folder i have a class called User like id, username  etc.

I read on the internet that I should do as less as possible in the controller. What do they mean?

I want to determine where to put the business logic For example I want to page a login page. What would happen if I put the login function alongside the models?

```<code>using IndividueleOpdracht.Dal;

namespace IndividueleOpdracht.Models
{
    public class AccountModel
    {
        public void Login(string username, string password)
        {
            // Do something with the repositories?
        }
    }
}
</code>```

And then just call the AccountModel.Login method in the controller?

答:
I read on the internet that I should do as less as possible in the
  controller. What do they mean?

They mean the Controller is a part of the UI. And you should do only UI-related things inside it. If you need to so something with your model data, you place those actions into another layer (bussiness layer, logic layer, call it whatever you like) and call that layer from the controller.

I want to determine where to put the business logic For example I want
  to page a login page. What would happen if I put the login function
  alongside the models?

You need to follow SRP when determining where to put things. Login does not look to me like a method of the user model itself. More like it belongs to authorization / authentication module of your business layer. But you decide of course.

Title: Business logic in the models?


问:
Why do we need both Priority and Severity?
I understand what they determine but is it really useful to assign those to issues found? I mean, it is either required to fixed quickly or not.

I know how to set them, categorize them etc. I know IEEE/ISO do require to do that. I just do not see why.

答:
You wrote:

I mean, it is either required to fixed quickly or not.

That is correct. If you are like most companies, however, your resources are limited. Either you don't have enough people to fix all of the issues, or you don't have enough time.

Given the fact that a bug is either required to be fixed quickly or not, and you have lots of bugs that need to get fixed, "priority" answers the question "which one do I fix first"?

Severity, on the other hand, is an indicator used by the person setting the priority. From a developer's point of view the severity is a moot point. From the perspective of the one assigning work, severity is an important piece of information that helps with the decision making process.

Of course, all of this is very general information. If you are a team with an impossibly long backlog of bugs, priority and severity mean something completely different than if you are on a team that has a near-empty bug database.

If you're on a team where "high severity == high priority" none of this matters and you don't need both metrics. At the end of the day, these are just tools. Your team needs to decide how to use them. For your team it may not make sense to use both.


答:
Deconstruct. Break whatever you're building into smaller features that you can implement in stages. Then, whenever you have any of those smaller pieces done and you've tested to confirm it doesn't break anything, deploy it and show it to the Powers That Be.

Using small iterations will often help you finish the larger project faster and better, because you're getting feedback as you go and you won't need to backtrack and redo as much. But even if it doesn't, you're showing constant progress, which has a solid psychological benefit and restores your manager or client's confidence.

Test-driven development also helps a lot with this approach. At first it may seem like writing tests first slows things down -- but it gains that time back in bugs you'll avoid, and depending on how you write them, the tests themselves could be a deliverable you can show to the Powers That Be and confirm the app's behavior even before you write it all.

Title: How to become a "faster" programmer?

OwnerDisplayName: SFEley


问:
Best practice for Restful API that perform heavy calculations (Image Processing)
We are currently developing an image processing restful api. Server performs some CPU-heavy computations image processing upon request and return the image to the client.

We want to make this a single http request (all computation should be done).

My questions.

What is the best workflow for this. With speed has an high factor.

Other alternatives suggest using a Master/Worker Server workflow. But will mean multiple requests (first to put job in queue, others to poll if job is done). We want to make it a one trip request. How can we achieve this?

The single request would most definitely take some time how do we handle timeouts

One more thing, we are using NodeJS.

答: You should submit your requests using a POST, and your service should return a URL that will retrieve the image once it's been processed. If the URL is accessed before the processing is complete, you should return a 202 (ACCEPTED) response. Once processing is complete, you can serve the processed image.</p>


问:
What is the recommended strategy to deal with a frequently changing database model during development
A lot of projects have a to be determined database model during early development. This could mean that a lot of SQL will have to be rewritten frequently. What is the recommended strategy to deal with this? Especially when you want to develop your application RAD-like and with the ultimate requirements not being set in stone at all? Mostly toy projects.

An ideal scenario would be that I can just not write any SQL at all at the start of the project, and only when the data model is more solidified, actually set up the database for the project and write SQL for it. During the initial development phase I just want to be able to alter my entity classes, without having to change my SQL over and over again.

(For the project I'm asking this, I'm working with Spring 4 and a MySQL database)

答:
The technique we're using on my current project (which will probably work for you) is to use Liquibase. All database changes are made via configuration files, which are checked in to source control and run automatically at application startup. This helps to keep your database schema in sync with the code -- whenever you pull the latest revision to your branch, you get the latest database configuration with it. It gets a little cumbersome if you do much more than add tables or columns, but IME most of the changes made during new system development are just that.

I believe there are several other "code first"-style ORM products out there, but this is the only one I'm really familiar with. Well, that and the .NET Entity Manager, but since you're using Spring 4 I assume you're working with Java. Be aware that other code-first solutions may require you to entirely drop and re-create your database when the schema changes. Usually this isn't a problem during early development, but can become a hassle later on.


答:
Most basic use of stack is to store return address for functions:

```<code>void a(){
    sub();
}
void b(){
    sub();
}
void sub() {
    //should i got back to a() or to b()?
}
</code>```

and from C point of view this is all. From compiler point of view:

all function arguments are passed by CPU registers - if there is not enough registers the arguments will be put on stack

after function ends (most) registers should have same values as before entering it - so used registers are backed up on stack

And from OS point of view: program can be interrupted any time so after we are done with system task we have to restore CPU state, so lets store everything on stack

All of this works since we don't care how much items are already on stack or how many items someone else will add in future, we just need to know how much we moved the stack pointer and restore it after we are done.

Body:
Most basic use of stack is to store return address for functions:

void a(){
    sub();
}
void b(){
    sub();
}
void sub() {
    //should i got back to a() or to b()?
}

and from C point of view this is all. From compiler point of view:

all function arguments are passed by CPU registers - if there is not enough registers the arguments will be put on stack

after function ends (most) registers should have same values as before entering it - so used registers are backed up on stack

And from OS point of view: program can be interrupted any time so after we are done with system task we have to restore CPU state, so lets store everything on stack

All of this works since we don't care how much items are already on stack or how many items someone else will add in future, we just need to know how much we moved the stack pointer and restore it after we are done.


答:
I prefer to work in vertical slices of functionality rather than keep the whole data layer uninmplemented until the end.

A lot of ORMs have a database generation feature. It doesn't need to be sophisticated and support DB schema diffs, since in development you often don't really care about your data and don't mind recreating the DB from scratch. However, that can be a nice asset for the future when your application goes in maintenance mode.

Title: What is the recommended strategy to deal with a frequently changing database model during development

Body:
A lot of projects have a to be determined database model during early development. This could mean that a lot of SQL will have to be rewritten frequently. What is the recommended strategy to deal with this? Especially when you want to develop your application RAD-like and with the ultimate requirements not being set in stone at all? Mostly toy projects.

An ideal scenario would be that I can just not write any SQL at all at the start of the project, and only when the data model is more solidified, actually set up the database for the project and write SQL for it. During the initial development phase I just want to be able to alter my entity classes, without having to change my SQL over and over again.

(For the project I'm asking this, I'm working with Spring 4 and a MySQL database)


答: If you are programming in C then learning bit hacks is a must for becoming a faster programmer. Also read coding practices by top rankers at Topcoder.com. Their code is very small and efficient.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: avd


问:
How is defining that a method can be overridden a stronger commitment than defining that a method can be called?
From : http://www.artima.com/lejava/articles/designprinciples4.html

Erich Gamma: I still think it's true even after ten years. Inheritance is a cool way to change behavior. But we know that it's brittle, because the subclass can easily make assumptions about the context in which a method it overrides is getting called. There's a tight coupling between the base class and the subclass, because of the implicit context in which the subclass code I plug in will be called. Composition has a nicer property. The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called.

I don't understand what he means. Could anyone please explain it?

答:
A commitment is something that reduces your future options. Publishing a method implies that users will call it, therefore you can't remove this method without breaking compatibility. If you'd kept it private, they couldn't (directly) call it, and you could some day refactor it away without problems. Therefore, publishing a method is a stronger commitment than not publishing it. Publishing an overridable method is an even stronger commitment. Your users can call it, and they can create new classes where the method doesn't do what you think it does!

For instance, if you publish a clean-up method, you can ensure that resources are properly deallocated as long as users remember to call this method as the last thing they do.
But if the method is overridable, someone might override it in a subclass and not call super. As a result, a third user might use that class and cause a resource leak even though they dutifully called cleanup() at the end! This means that you can no longer guarantee the semantics of your code, which is a very bad thing.

Essentially, you can no longer rely on any code running in user-overridable methods, because some middleman might override it away. This means that you have to implement your clean-up routine entirely in private methods, with no help from the user. Therefore it's usually a good idea to publish only final elements unless they are explicitly intended for overriding by API users.


答:
If you publish a normal function, you give a one-sided contract:

What does the function do if called?

If you publish a callback, you also give a one-sided contract:

When and how will it be called?

And if you publish an overridable function, it's both at once, so you give a two-sided contract:

When will it be called, and what must it do if called?

Even if your users aren't abusing your API (by breaking their part of the contract, which might be prohibitively expensive to detect), you can easily see that the latter needs far more documentation, and everything you document is a commitment, which limits your further choices.

An example of reneging on such a two-sided contract is the move from show and hide to setVisible(boolean) in java.awt.Component.

Title: How is defining that a method can be overridden a stronger commitment than defining that a method can be called?

Body:
From : http://www.artima.com/lejava/articles/designprinciples4.html

Erich Gamma: I still think it's true even after ten years. Inheritance is a cool way to change behavior. But we know that it's brittle, because the subclass can easily make assumptions about the context in which a method it overrides is getting called. There's a tight coupling between the base class and the subclass, because of the implicit context in which the subclass code I plug in will be called. Composition has a nicer property. The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called.

I don't understand what he means. Could anyone please explain it?

ContentLicense: CC BY-SA 4.0


答:
Kilian Foth's answer is excellent.  I'd just like to add the canonical example* of why this is a problem.  Imagine an integer Point class:

class Point2D {
    public int x;
    public int y;

    // constructor
    public Point2D(int theX, int theY) { x = theX; y = theY; }

    public int hashCode() { return x + y; }

    public boolean equals(Object o) {
        if (this == o) { return true; }
        if ( !(o instanceof Point2D) ) { return false; }

        Point2D that = (Point2D) o;

        return (x == that.x) &&
               (y == that.y);
    }
}
```
<p>Now let's sub-class it to be a 3D point.</p>
<pre class="lang-java prettyprint-override"><code>class Point3D extends Point2D {
    public int z;

    // constructor
    public Point3D(int theX, int theY, int theZ) {
        super(x, y); z = theZ;
    }

    public int hashCode() { return super.hashCode() + z; }

    public boolean equals(Object o) {
        if (this == o) { return true; }
        if ( !(o instanceof Point3D) ) { return false; }

        Point3D that = (Point3D) o;

        return super.equals(that) &&
               (z == that.z);
    }
}
</code>```

Super simple!  Let's use our points:

Point2D p2a = new Point2D(3, 5);
Point2D p2b = new Point2D(3, 5);
Point2D p2c = new Point2D(3, 7);

p2a.equals(p2b); // true
p2b.equals(p2a); // true
p2a.equals(p2c); // false

Point3D p3a = new Point3D(3, 5, 7);
Point3D p3b = new Point3D(3, 5, 7);
Point3D p3c = new Point3D(3, 7, 11);

p3a.equals(p3b); // true
p3b.equals(p3a); // true
p3a.equals(p3c); // false
```
<p>You are probably wondering why I'm posting such an easy example.  Here's the catch:</p>
<pre class="lang-java prettyprint-override"><code>p2a.equals(p3a); // true
p3a.equals(p2a); // FALSE!
</code>```

When we compare the 2D point to the equivalent 3D point, we get true, but when we reverse the comparason, we get false (because p2a fails instanceof Point3D).

Conclusion

It is usually possible to implement a method in a subclass in such a way  that it's no-longer compatible with how the super-class expects it to work.

It is generally impossible to implement equals() on a significantly different subclass in a way that is compatible with it's parent class.

When you write a class that you intend to allow people to subclass, it's a really good idea to write out a contract for how each method should behave.  Even better would be a set of unit tests people could run against their implementations of overridden methods to prove that they do not violate the contract.  Almost nobody does that because it's too much work.  But if you care, that's the thing to do.

A great example of a well-spelled out contract is Comparator.  Just ignore what it says about .equals() for the reasons described above.  Here's an example of how Comparator can do things .equals() can't.

Notes

Josh Bloch's "Effective Java" Item 8 was the source of this example, but Bloch uses a ColorPoint which adds a color instead of a third axis and uses doubles instead of ints.  Bloch's Java example is basically duplicated by Odersky/Spoon/Venners who made their example available online.

Several people have objected to this example because if you let the parent class know about the sub-class, you can fix this issue.  That's true if there are a small enough number of sub-classes and if the parent knows about them all.  But the original question was about making an API which someone else will write sub-classes for.  In that case, you generally can't update the parent implementation to be compatible with the sub-classes.

Bonus

Comparator is also interesting because it works around the issue of implementing equals() correctly.  Better yet, it follows a pattern for fixing this type of inheritance issue: the Strategy design pattern.  The Typeclasses that Haskell and Scala people get excited about are also the Strategy pattern.  Inheritance isn't bad or wrong, it's just tricky.  For further reading, check out Philip Wadler's paper How to make ad-hoc polymorphism less ad hoc

Body:
Kilian Foth's answer is excellent.  I'd just like to add the canonical example* of why this is a problem.  Imagine an integer Point class:

class Point2D {
    public int x;
    public int y;

    // constructor
    public Point2D(int theX, int theY) { x = theX; y = theY; }

    public int hashCode() { return x + y; }

    public boolean equals(Object o) {
        if (this == o) { return true; }
        if ( !(o instanceof Point2D) ) { return false; }

        Point2D that = (Point2D) o;

        return (x == that.x) &&
               (y == that.y);
    }
}

Now let's sub-class it to be a 3D point.

class Point3D extends Point2D {
    public int z;

    // constructor
    public Point3D(int theX, int theY, int theZ) {
        super(x, y); z = theZ;
    }

    public int hashCode() { return super.hashCode() + z; }

    public boolean equals(Object o) {
        if (this == o) { return true; }
        if ( !(o instanceof Point3D) ) { return false; }

        Point3D that = (Point3D) o;

        return super.equals(that) &&
               (z == that.z);
    }
}

Super simple!  Let's use our points:

Point2D p2a = new Point2D(3, 5);
Point2D p2b = new Point2D(3, 5);
Point2D p2c = new Point2D(3, 7);

p2a.equals(p2b); // true
p2b.equals(p2a); // true
p2a.equals(p2c); // false

Point3D p3a = new Point3D(3, 5, 7);
Point3D p3b = new Point3D(3, 5, 7);
Point3D p3c = new Point3D(3, 7, 11);

p3a.equals(p3b); // true
p3b.equals(p3a); // true
p3a.equals(p3c); // false

You are probably wondering why I'm posting such an easy example.  Here's the catch:

p2a.equals(p3a); // true
p3a.equals(p2a); // FALSE!

When we compare the 2D point to the equivalent 3D point, we get true, but when we reverse the comparason, we get false (because p2a fails instanceof Point3D).

Conclusion

It is usually possible to implement a method in a subclass in such a way  that it's no-longer compatible with how the super-class expects it to work.

It is generally impossible to implement equals() on a significantly different subclass in a way that is compatible with it's parent class.

When you write a class that you intend to allow people to subclass, it's a really good idea to write out a contract for how each method should behave.  Even better would be a set of unit tests people could run against their implementations of overridden methods to prove that they do not violate the contract.  Almost nobody does that because it's too much work.  But if you care, that's the thing to do.

A great example of a well-spelled out contract is Comparator.  Just ignore what it says about .equals() for the reasons described above.  Here's an example of how Comparator can do things .equals() can't.

Notes

Josh Bloch's "Effective Java" Item 8 was the source of this example, but Bloch uses a ColorPoint which adds a color instead of a third axis and uses doubles instead of ints.  Bloch's Java example is basically duplicated by Odersky/Spoon/Venners who made their example available online.

Several people have objected to this example because if you let the parent class know about the sub-class, you can fix this issue.  That's true if there are a small enough number of sub-classes and if the parent knows about them all.  But the original question was about making an API which someone else will write sub-classes for.  In that case, you generally can't update the parent implementation to be compatible with the sub-classes.

Bonus

Comparator is also interesting because it works around the issue of implementing equals() correctly.  Better yet, it follows a pattern for fixing this type of inheritance issue: the Strategy design pattern.  The Typeclasses that Haskell and Scala people get excited about are also the Strategy pattern.  Inheritance isn't bad or wrong, it's just tricky.  For further reading, check out Philip Wadler's paper How to make ad-hoc polymorphism less ad hoc


问:
What design pattern best suits managing handles to objects, without passing handles or Manager around?
I'm writing a game in C++ using OpenGL.

For those that don't know, with the OpenGL API you make a lot of calls to things like glGenBuffers and glCreateShader etc. These return types of GLuint which are unique identifiers to what you just created. The thing being created lives on the GPU memory.

Considering that GPU Memory is sometimes limited, you don't want to create two things that are the same when they're to be used by multiple objects.

For example, Shaders. You link a Shader Program and then you have a GLuint. When you're done with the Shader, you should call glDeleteShader (or something to that affect).

Now, let's say I have a shallow class hierarchy like:

```<code>class WorldEntity
{
public:
    /* ... */
protected:
    ShaderProgram* shader;
    /* ... */
};

class CarEntity : public WorldEntity
{
    /* ... */
};

class PersonEntity: public WorldEntity
{
    /* ... */
};
</code>```

Any code I've ever seen would require that all the Constructors have a ShaderProgram* passed to it to be stored in the WorldEntity. ShaderProgram is my class that encapsulates the binding of a GLuint to the current shader state in the OpenGL context as well as a few other helpful things that you need to do with Shaders.

The problem I have with this is:

There's a lot of parameters needed to construct a WorldEntity (consider that there might be a mesh, a shader, a bunch of textures etc, all of which could be shared, so they're passed as pointers)

Whatever is creating the WorldEntity needs to know what ShaderProgram it needs

This probably requires some sort of gulp EntityManager class that knows what instance of what ShaderProgram to pass to different entities.

So now because there's a Manager the classes need to either register themselves with the EntityManager along with the ShaderProgram instance they need, or I need a big-ass switch in the manager that I need to update for every new WorldEntity derived type.

My first thought was to create a ShaderManager class (I know, Managers are bad) that I pass by reference or pointer to the WorldEntity classes so that they can create whatever ShaderProgram they want, via the ShaderManager and the ShaderManager can keep track of already existing ShaderPrograms, so it can return one that already exists or create a new one if needed.

(I could store the ShaderPrograms via the hash of the filenames of the ShaderPrograms actual source code)

So now:

I'm now passing pointers to ShaderManager instead of ShaderProgram, so there's still a lot of parameters

I don't need an EntityManager, the entities themselves will know what instance of ShaderProgram to create, and ShaderManager will handle the actual ShaderPrograms.

But now I don't know when ShaderManager can safely delete a ShaderProgram that it holds.

SO now I've added reference counting to my ShaderProgram class that deletes its internal GLuint via glDeleteProgram and I do away with ShaderManager.

So now:

An object can create whatever ShaderProgram it needs

But now there's duplicate ShaderPrograms because there's no external Manager keeping track

Finally I come to make one of two decisions:

1. Static Class

A static class that's invoked to create ShaderPrograms. It keeps an internal track of ShaderPrograms based on a hash of the filenames
- this means I no longer need to pass pointers or references to ShaderPrograms or ShaderManagers around, so less parameters
- The WorldEntities have all knowledge about the instance of ShaderProgram they want to create

This new static ShaderManager needs to:

keep a count of the number of times a ShaderProgram is used and I make ShaderProgram no copyable OR

ShaderPrograms count their references and only call glDeleteProgram in their destructor when the count is 0 AND ShaderManager periodically checks for ShaderProgram's with a count of 1 and discards them.

The downsides to this approach I see are:

I have global static class which might be a problem. The OpenGL Context needs to be created prior to the invoking any glX functions. So potentially, a WorldEntity might be created and try to create a ShaderProgram prior to OpenGL Context creation, which will result in a crash.

The only way around this is back to passing everything around as pointers/references, or having a global GLContext class that can be queried, or holding everything in a class that creates the Context on construction. Or maybe just a global boolean IsContextCreated that can be checked. But I worry that this gives me ugly code everywhere.

What I can see the devolving to is:

The big Engine class that has every other class hidden inside of it so that it can control the construction/deconstruction order appropriately. This seems like a big mess of interface code between the user of the engine and the engine, like a wrapper over a wrapper

A whole slew of "Manager" classes that keep track of instances and delete things when neccessary. This might be a necessary evil?

AND

When to actually clear ShaderPrograms out of the static ShaderManager? Every few minutes? Every Game Loop? I'm gracefully handling the re-compiling of a shader in the case when a ShaderProgram was deleted but then a new WorldEntity requests it; but I'm sure there's a better way.

2. A better method

That's what I'm asking for here

答:
Instead of doing reference counting in the ShaderProgram class itself, it is better to delegate that to a smart pointer class, like std::shared_ptr<>. That way, you ensure that each class only has a single job to do.

To avoid accidentally exhausting your OpenGL resources, you can make ShaderProgram non-copyable (private/deleted copy-constructor and copy-assignment operator).

To keep a central repository of ShaderProgram instances that can be shared, you could use a SharedShaderProgramFactory (similar to your static manager, but with a better name) like this:

```<code>class SharedShaderProgramFactory {
private:
  std::weak_ptr<ShaderProgram> program_a;

  std::shared_ptr<ShaderProgram> get_progam_a()
  {
    shared_ptr<ShaderProgram> temp = program_a.lock();
    if (!temp)
    {
      // Requested program does not currently exist, so (re-)create it
      temp = new ShaderProgramA();
      program_a = temp; // Save for future requests
    }
    return temp;
  }
};
</code>```

The factory class can be implemented as a static class, a Singleton or a dependency that gets passed where needed.

Body:
Instead of doing reference counting in the ShaderProgram class itself, it is better to delegate that to a smart pointer class, like std::shared_ptr<>. That way, you ensure that each class only has a single job to do.

To avoid accidentally exhausting your OpenGL resources, you can make ShaderProgram non-copyable (private/deleted copy-constructor and copy-assignment operator).

To keep a central repository of ShaderProgram instances that can be shared, you could use a SharedShaderProgramFactory (similar to your static manager, but with a better name) like this:

class SharedShaderProgramFactory {
private:
  std::weak_ptr<ShaderProgram> program_a;

  std::shared_ptr<ShaderProgram> get_progam_a()
  {
    shared_ptr<ShaderProgram> temp = program_a.lock();
    if (!temp)
    {
      // Requested program does not currently exist, so (re-)create it
      temp = new ShaderProgramA();
      program_a = temp; // Save for future requests
    }
    return temp;
  }
};

The factory class can be implemented as a static class, a Singleton or a dependency that gets passed where needed.


答:
Get stable, stay stable.

Build something that implements a small bit of the functionality, and make sure it works, end-to-end.  Then, keep it working as you add new bits of functionality.  Yeah, this is partly a TDD practice, but it makes sense even if you don't do TDD.

The rationale is that every time I've seen someone with 2 weeks of code that had never been stable, it always takes another 2 weeks to get it stable.

If you stay stable, you remove that uncertainty, and also give yourself a way to scope down near the deadline if necessary.

The obvious counter-argument is that doing this will take more time than just writing it once, as you will do extra work be stabilizing non-final code.  I don't buy this for a second.  When you have code that works, you change 5 lines, and something breaks, you know exactly where the break must have happened.

If you have 10,000 lines of code that never worked, and you have to find a break, you have a ton of code to search through.

Small, incremental changes on a system that is consistently stable FTW.  Go slow to go fast.

Title: How to become a "faster" programmer?

OwnerDisplayName: kyoryu


答:
This answer refers specifically to the stack pointer of the current thread (of execution).

In procedural programming languages, a thread typically has access to a stack1 for the following purposes:

Control flow, namely "call stack".

When one function calls another function, the call stack remembers where to return to.

A call stack is necessary because this is how we want a "function call" to behave - "to pick up where we left off".

There are other programming styles that do not have function calls in the middle of execution (e.g. only allowed to specify the next function when the end of the current function is reached), or have no function calls at all (only using goto and conditional jumps). These programming styles might not need a call stack.

Function call parameters.

When a function calls another function, parameters can be pushed onto the stack.

It is necessary for the caller and the callee to follow the same convention as to who is responsible for clearing the parameters from the stack, when the call finishes.

Local variables that live within a function call.

Note that a local variable belonging to a caller can be made accessible to a callee by passing a pointer to that local variable to the callee.

Note1: dedicated to the thread's use, although its content is entirely readable - and smashable - by other threads.

In assembly programming, C, and C++, all three purposes can be fulfilled by the same stack. In some other languages, some purposes may be fulfilled by separate stacks, or dynamically-allocated memory.


答:
Here is a deliberately oversimplified version of what the stack is used for.

Imagine the stack as a pile of index cards.  The stack pointer points to the top card.

When you call a function:

You write the address of the code immediately after the line that called the function on a card and put it on the pile.  (I.e. you increment the stack pointer by one and write the address to where it points to)

Then you write down the values contained in registers onto some cards,
and put them on the pile.  (i.e. you increment the stack pointer by the number of registers, and copy the register contents to the place it points to)

Then you put a marker card on the pile. (i.e. you save off the current stack pointer.)

Then you write the value of each parameter the function is called with, one to a card, and put it on the pile.  (i.e you increment the stack pointer by the number of parameters and write the parameters to the place the stack pointer points to.)

Then you add a card for each local variable, potentially writing the initial value on it.  (i.e. you increment the stack pointer by the number of local variables.)

At this point, the code in the function runs.  The code is compiled to know where each card is relative to the top.  So it knows that the variable x is the third card from the top (i.e. the stack pointer - 3) and that the parameter y is the sixth card from the top (i.e. the stack pointer - 6.)

This method means that the address of each local variable or parameter does not need to be baked into the code.  Instead, all of these data items are addressed relative to the stack pointer.

When the function returns, the reverse operation is simply:

Look for the marker card and throw all the cards above it away.  (i.e. set the stack pointer to the saved address.)

Restore the registers from the cards saved before and throw them away.  (i.e. subtract a fixed value from the stack pointer)

Start running code from the address on the card on top and then throw that away.  (i.e. subtract 1 from the stack pointer.)

The stack is now back in the state it was before the function was called.

When you consider this, note two things: allocation and deallocation of locals is an extremely fast operation as it is just adding a number to or subtracting a number from the stack pointer.  Also note how naturally this works with recursion.

This is oversimplified for explanatory purposes.  In practice, parameters and locals may be put in registers as an optimization, and the stack pointer will generally be incremented and decremented by the word size of the machine, not one.  (To name a couple of things.)


问:
What package name to choose for a small, open-source Java project?
I'd like to publish a small open-source library in Java. I wonder what package name should I choose? I'm not a company and I don't have a domain that I could use as the basis for naming the package according to the naming conventions. Still I'd like to somehow follow the naming conventions to prevent an accidental conflict and to keep things standard.</p>

答:
Your profile on Software Engineering implies that you control petr.pudlak.name, which gives name.pudlak.petr.exampleproject as a possibility.

Another technique to ensure uniqueness is to base it on the means through which the program is distributed to the public. If the username associated with your GitHub repositories is petrpudlak, something like com.github.petrpudlak.exampleproject should avoid collision. The same is true of SourceForge projects: net.sourceforge.exampleproject.


问:
Handling Value Unit data
We have some data that is strongly bound to each other and we are using it for calculations. Its a value with a unit type and an optional relation.
E.g. 1500 meter above sea level.
The unit type should be replaceable (meter to foot). But the value should be converted accordingly.

I am currently thinking of two approaches:

Approach 1 saves the value in a fixed unit to the database without an conversion. The conversion would be made on the fly after loading the value with its prefered unit type.
e.g. always saved in meter, but will be displayed in foot if the unit was changed
+ This prohibits problems from converting the value back and forth while causing rounding errors.
+ Calculations with the data can be done without converting it, since the saved value is always in meter
- If you enter a value in foot but save it as meter and reload it, it could show not the value you entered because of a rounding error.

Approach 2 saves the value in the selected unit. But that switches the advantages with the disadvantages. And it would make it probably hard to choose a good databasetype for saving it since the unit is not always the same.

I tried to find how other people work with this kind of relation but since "unit" is a pretty strong word i can't find anything related to my problem.
But I think this value/unit data structure is not so rare.

How should I approach this kind of data?

How should I save and load it?

When should I convert the data?

Am I missing some problems that could influence my decision?

答:
I believe the term you're looking for is "unit of measure" as that more clearly conveys the concept of a value and some sort of units associated with the value.

And as you're starting to see, there are quite a few approaches to handling the challenges you're running into.

For runtime operations, the solutions range from just using "implied" units, having the units built into the variable name, having a separate property for the units, to using an object or class that presents as an actual unit of measure (e.g. value and unit combined).  There's a trade-off here between level of effort to implement, convert, and use against the risks of failure within your code.

Database operations are a bit more difficult to categorize with the primary challenge being the inability to represent an actual unit of measure.  I have seen solutions using implied" units and units attached to the column name.

I have also seen using a second column to represent the units.  Depending upon how you structure that, that column could be a simple string representation or it could be a foreign key index into another fixed table indicating unit type.

To answer some of your questions -

The first thing you need to do is assess how much of an impact this has upon your codebase.  If you're using a lot of units and doing a lot of conversions, then you'll likely want a more robust solution.  Vice versa, if this only crops up every now and then, you may be able to get away with a simpler solution.

I would avoid performing a lot of unnecessary conversions, if possible.  As you noted, it does introduce error which can throw off calculations.  Generally, pick the most commonly used form and use that as your "base unit" to work from.  But temper that advice based upon the particulars of what you're doing and realize that you don't have to strictly follow normalization rules if it simplifies your initial design and long term maintenance.

Title: Handling Value Unit data


答:
This can get tricky because repeatedly converting between units can accumulate rounding errors.

For example, taking a value in meters, converting to feet, and back to meters might show a slight error such as 1 meter and 0.9999 meters. Or, for a less obvious example, 4.587 meters converting to feet and back might give 4.585 meters.

The more you change values, the more inaccurate they may be. Since Computer Science often looks at minimizing the worst case, we need to assume the worst in order to show the value can never deviate more than a certain amount.

To achieve this goal, you should always store the value in the most precise way possible, and convert on the fly as needed and never more than once.

I would store amount and unit fields representing e.g. "4.5 meters" and always use that as a base. If I need feet, then convert it to feet: if I need miles, convert meters to miles, not meters to feet to miles.

Approach two may be more computationally-intensive in the long run, but it is more accurate. Given these computations are not exactly complex or expensive to begin with and that modern computers are extremely powerful, I would sacrifice efficiency for accuracy.

I also recommend setting up a conversion table using as much precision as possible. This will never change unless new units are added, so a static, high-precision table is a safe bet and will help ensure consistency and accuracy.

Title: Handling Value Unit data

Body:
We have some data that is strongly bound to each other and we are using it for calculations. Its a value with a unit type and an optional relation.
E.g. 1500 meter above sea level.
The unit type should be replaceable (meter to foot). But the value should be converted accordingly.

I am currently thinking of two approaches:

Approach 1 saves the value in a fixed unit to the database without an conversion. The conversion would be made on the fly after loading the value with its prefered unit type.
e.g. always saved in meter, but will be displayed in foot if the unit was changed
+ This prohibits problems from converting the value back and forth while causing rounding errors.
+ Calculations with the data can be done without converting it, since the saved value is always in meter
- If you enter a value in foot but save it as meter and reload it, it could show not the value you entered because of a rounding error.

Approach 2 saves the value in the selected unit. But that switches the advantages with the disadvantages. And it would make it probably hard to choose a good databasetype for saving it since the unit is not always the same.

I tried to find how other people work with this kind of relation but since "unit" is a pretty strong word i can't find anything related to my problem.
But I think this value/unit data structure is not so rare.

How should I approach this kind of data?

How should I save and load it?

When should I convert the data?

Am I missing some problems that could influence my decision?


答:
The stack pointer is used (with the frame pointer) for the call stack (follow the link to wikipedia, where there is a good picture).

The call stack contains call frames, which contain return address, local variables and other local data (in particular, spilled content of registers; formals).

Read also about tail calls (some tail-recursive calls don't need any call frame), exception handling (like setjmp & longjmp, they may involve popping many stack frames at once), signals & interrupts, and continuations. See also calling conventions and application binary interfaces (ABIs), in particular the x86-64 ABI (which defines that some formal arguments are passed by registers).

Also, code some simple function(s) in C, then use gcc -Wall -O -S -fverbose-asm  to compile it, and look into the generated .s  assembler file.

Appel wrote an old 1986 paper claiming that garbage collection can be faster than stack allocation (using Continuation-Passing Style in the compiler), but this is probably false on today's x86 processors (notably because of cache effects).

Notice that calling conventions, ABIs, and stack layout are different on 32 bits i686 and on 64 bits x86-64. Also, calling conventions (and who is responsible for allocating or popping the call frame) may be different with different languages (e.g. C, Pascal, Ocaml, SBCL Common Lisp have different calling conventions ....)

BTW, recent x86 extensions like AVX are imposing increasingly large alignment constraints on the stack pointer (IIRC, a call frame on x86-64 wants to be aligned to 16 bytes, i.e. two words or pointers).


问:
Should all, none, or some overridden methods call Super?
When designing a class, how do you decide when all overridden methods should call super or when none of the overridden methods should call super? Also, is it considered bad practice if your code logic requires a mixture of supered and non-supered methods like the Javascript example below?

```<code>ChildClass = new Class.create(ParentClass,
{
   /**
    * @Override
    */
   initialize: function($super) {
      $super();
      this.foo = 99;
   },

   /**
    * @Override
    */
   methodOne: function($super) {
      $super();
      this.foo++;
   },

   /**
    * @Override
    */
   methodTwo: function($super) {
      this.foo--;
   }
});
</code>```

After delving into the iPhone and Android SDKs, I noticed that super must be called on every overridden method, or else the program will crash because something wouldn't get initialized. When deriving from a template/delegate, none of the methods are supered (obviously). So what exactly are these "je ne sais quoi" qualities that determine whether a all, none, or some overriden methods should call super?

答: Whether or not you should call super depends on whether you are trying to add to the existing functionality of the method or to replace it. That is totally dependent on what the method is doing and in some cases may even depend on the parameters.</p>


答:
Write your own productivity tools.  They may take time initially to write, but the pay off can be big over time.

Some tools that I've written that I use all the time:

An SQL formatter.

An automatic SQL generator: just
select the tables.

A simple task prioritiser, so I can see all my tasks in one go.

A task reminder that nags me
periodically.

An app that takes delimited text and
allows you to treat it like a
spreadsheet and like text.

A PHP/Javascript/HTML page formatter.
A godsend when working with others'
code.

I've written lots of other small tools in my time that have fallen by the wayside, but it was still worth the effort.

Title: How to become a "faster" programmer?

OwnerDisplayName: Jonathan Swift


问:
Is the behaviour of floating-point arithmetic defined by the c++ standard?
I started writing this as a SO question, but I think it's better suited here. While I'm happy for a simple answer I'm also fond of the "Teach a Man to Fish" philosophy so I'm happy for people to point me to documentation.

Is floating-point arithmetic fully locked down by the standard?

In other words, suppose I have a fully compliant c++ program compiled with a fully compliant compiler that performs every possible combination of floating point operation. Will such a program perform identically on any machine with the same data model, regardless of which compliant compiler I use?

Where can I learn more about floating point arithmetic as defined by the C++ standard (I don't have a copy)?

答: The C++ standard does not fully define floating point behaviour. However, there are floating point standards, like IEEE 754, that are widely supported by C++ compilers (at least among the compilers that support hardware targets that have proper floating point support).</p>