问:
How to know what to test in TDD?
I've heard about TDD more than one year ago, but until now I didn't manage to get myself started with it. Indeed, one of my greatest doubts is always what to test. The examples given always shows test to verify if some business rule is being correctly implemented.

So, for instance, in an auction software we have the business rule "an user can only post a bid on a item if the value is greater than the value of the last bid". That is fine, this kind of thing is easy to imagine we need to ensure to be working. Those are things the end user of the system would care.

But sometimes we are working on the infrastructure of the system. Authentication and authorization, selection of resources for users, security verifications and so on. On these cases it doesn't seems obvious at first what should we test.

So, currently I'm not yet using TDD because always when I think to do so I find myself questioning "ok, now what tests should I write" and I never know how to answer this question. How can I know which tests I should write when starting to build an app?

答:
Look, your software has to do something or else you wouldn't be writing it. "I need something to verify people's credentials." Is a perfectly fine high level requirement to start making tests from.

TDD is at its core a framework for you to ask "what is this thing going to do?". You want to authenticate and authorize users? Great. Now write your ideal code that authenticates and authorizes users (in the form of a test). This gets you to actually define what your code needs to do, as well as a nice interface for someone to use it (since you started by using it). Making the actual working code to fill in the gaps comes last because for almost all code, the interface matters more than the implementation.

What to test is simply what you're trying to implement rather than how you mean to implement it. If you don't even know what you're trying to accomplish, then maybe you should stop writing code and go figure that out first.

Title: How to know what to test in TDD?


问:
Are there any algorithms for splitting or combining words into their more common form?
Are there any existing algorithms which can look through a list of words and split or combine words into their more common form?

For example, I have a list of many business names in the health care industry. The word "healthcare" is often written "health care". There are also business names which might be split or combined, such as "Walmart" and "Wal mart".

Are there any algorithms which can look at my list of words and identify that "healthcare" is more often written as two words, and that "Wal mart" is more often written as a single word?

I'm looking for the names of existing algorithms (which can help when searching the web), or links to existing white-papers or blog posts.

I'd prefer an algorithm that doesn't depend on a dictionary or other external list of words or business names.

EDITS:

Background:

I already have some code that is moderately successful at this task. The code was thrown together without much rigor. I hoped there were some established algorithms, which would likely be more academic and complete then what I've come up with. This question is not about the method I've come up with, but saying "it's impossible" doesn't convince me.

Clarification:

The "more common form" of a word is the way the word(s) are most often written. For example, "Walmart" appeared many times, and "Wal mart" appeared many times, but "Walmart" appeared more often then "Wal mart" and so "Walmart" is the "more common form" of the word.

I don't expect this algorithm to produce perfect results. Like any machine learning problem, I expect the results to be dependent on the quality of data I give it, and how much data I have.

答:
Generally I think you are after linguistic normalization and the algorithms that are applicable to your description of the problem are the algorithms that solve the problem of polysemy and collocations in particular.

The word "healthcare" is often written "health care" ...

The accepted defintion for collocations is a combination of adjacent words that have a common meaning. The hypernym of "health care" and "healthcare" is social insurance for the ill and injured, this is coincidently is also a related hypernym for "medicare" (though they are not exactly the same, but I presume you are interested in business names that could mention all the above).

The WordNet lexical database is one of the largest and you can use its search facilities to explore collocations and hypernyms.

The hypernyms, collocations and the semantic relationships are typically aggregated in a database, and I am unconvinced that,

... an algorithm that doesn't depend on a dictionary or other external list of words or business names.

is a viable approach. In the best case you would be essentially eschewing the shoulders of giants and slowly re-building what's already available in existing lexical databases and collocation dictionaries as your algorithms accumulates and stores the interpretation of the collocations you encounter in your tasks.

Here are some additional resources and links,

Oxford Collocation dictionary (1, 2)

BBI Dictionary of English Word Combinations

EuroWordNet

Longman Collocations Dictionary and Thesaurus

For locating the necessary reasearch papers and algorithms I suggest that you simply employ citeseer with collocations as the main term, it is fairly unique to natural language processing. I am not sure though as I expressed above that you will be able to find an online algorithm that doesn't rely on dictionaries or pre-existing learning corpora for your task.

ContentLicense: CC BY-SA 3.0


问:
Is retaining intermediate objects as member fields a good idea in this case?
I'm currently writing a series of classes in java that are meant to translate a regular expression (written with the formal definition, not language-specific shortcuts) into a deterministic finite automaton.

To make the DFA, it first converts the regex to postfix, then to a  syntax tree, then to an NFA, then finally to the DFA, which is then minimized.

Should I keep a reference to each intermediary object as a member of the object it was used to create? e.g. A reference to the syntax tree in the NFA, and a reference to the NFA in the DFA?

They're not publicly accessible, so are they just unnecessarily bloating the classes and the program?

答:
If your class is modelling the process -- that is, it's a throw-away worker object -- then it can work well to hold intermediate state as members. Think of the Builder pattern, which accumulates state information about what it's trying to build, and then produces the object -- then you toss the Builder.

I use one-shot classes like that when the process is really complicated & has lots of steps (which your case does). This can be really handy for isolating the different steps.

...

"Should I keep a reference to each intermediary object as a member of the object it was used to create?" I would not. In the context of the building process, those could be members of some external context, but the resulting classes should just be the thing itself. (Sort of at face value, having a class that holds the NFA and DFA violates the single responsibility principle.)


问:
How to test state of the object
I have a class DataImport
with only two public methods

```<code>public void fromStream(InputStream inputStream);
public ImportCommand getImportCommand();
</code>```

When I test it I send some test data to fromStream method

```<code>dataImport.fromStream(some stream with data...)
</code>```

Only way how to test the result of this method is to get the ImportCommand from getImportCommand and test if this object is in the state according to the input I provided.

But what if ImportCommand has only one method?

```<code>public ImportResult execute();
</code>```

I could test ImportResult (after invoking execute() which would involve some mocks and additional setup) because it has some state exposed. But this way I am testing ImportCommand and the DataImport class in one unit test which does not feel right to me.

But exposing inner state of the classes I am testing or accessing their private fields/methods also is not good thing.

Does this mean that my design is not ok (how should I change it) or is there some way how to solve this situation?

Related: TDD anti-patterns on SO

答:
In unit tests you should always test behavior of your objects not the state. TDD is helpful when you design you APIs, in this case you already decided how the API will look and you have problems how to test it.

IMO DataImport is unnecessary abstraction. It can be one method somewhere else.

Title: How to test state of the object


答:
Keeping a reference to intermediate objects within the constructed object sounds to me like a violation of the SRP principle. For example, you may have classes NFA, DFA, a class DFABuilder and a context from where you use those objects

the concern of the DFA class is to represent the deterministic finite automate  (similar NFA), no less, no more. The source from which a DFA has become constructed should not matter to the DFA object, it is simply not it' s concern.

the concern of the DFABuilder is to convert an NFA object to an DFA object (lets assume it has public method DFA ConvertNFAToDFA(NFA nfa). It may hold a reference to the NFA object for its lifetime, and produce more intermediate objects for this purpose, but after the construction is done, there should be no need to keep the DFABuilder object or it's intermediate objects alife (assumed there is no explicit requirement to access internals of the creation proccess afterwards.)

the concern of the context is to provide an NFA object, call ConvertNFAToDFA and receive the resulting DFA object for further processing.

So if you have the requirement to reuse the NFA object within the context after the construction of the DFA, keep a reference to the NFA at context scope. If you don't have the requirement, don't keep it. But in both cases there should be no need to store the NFA object directly within the DFA. If your program produces multiple NFA objects, DFA objects (and other related objects), and you want to keep track of which object was created from which other, you may consider to create an enclosing tuple class, for holding a pair of an NFA and a DFA object . But keeping the classes NFA and DFA completely separated from each other makes it much easier to reuse and test them.

Title: Is retaining intermediate objects as member fields a good idea in this case?

Body:
I'm currently writing a series of classes in java that are meant to translate a regular expression (written with the formal definition, not language-specific shortcuts) into a deterministic finite automaton.

To make the DFA, it first converts the regex to postfix, then to a  syntax tree, then to an NFA, then finally to the DFA, which is then minimized.

Should I keep a reference to each intermediary object as a member of the object it was used to create? e.g. A reference to the syntax tree in the NFA, and a reference to the NFA in the DFA?

They're not publicly accessible, so are they just unnecessarily bloating the classes and the program?


问:
How can I promote software reuse in a large company?
Take a large company, formed through many iterations of mergers and reorganizations. This company produces lots of different products that are all targeted to a specific industry. Most products share similar characteristics, such as communication standards and certification and safety requirements. But there is no unified development platform or model for the company. Each product has its own distinct hardware, and software is created in any number of languages. Most new products will be updates to older versions or target the same industry. What strategies would you use to promote software reuse?</p>

答:
The best way to make software reusable is to make it visible and understandable.

If nobody knows it exists, nobody will use it.

If nobody can figure out how to use it, nobody will use it.

For developers this means making good documentation and usecases.  I'll discuss Java since that is what I know the best:

Use JavaDoc:  This allows for creating cross-referenced API documentation where the skeleton is created automatically and you have well-defined places for putting in HTML-snippets in your code which will then end up in the web documentation.  See the official Java documentation for a good example.  In my opinion this is some of the best code based documentation available today.

Put the JavaDoc in a searchable place:  For people to be able to find it you need to make it public.  Have an internal web server where all documentation go to, probably subclassed by project.  In a perfect world have a SINGLE web site incorporating ALL classes developed inhouse.

Make it easy to get:  Have a location link from which it is extremely simple to pull out the source code (or the library).  Eclipse has some mechanics for doing so.  Preferably the source from a source repository, as the source repository can TELL who has worked on a given piece of code, giving a good idea of who to talk to in case that you need assistance with that code.

Have good usage examples: The easiest way to show how to use it, is with good unit tests, as they demonstrate how to use the code, and what to expect back.  Being runnable they can verify that the code runs as described.

ContentLicense: CC BY-SA 2.5


问:
How can I team up two MVC frameworks without having them fight each other?
I'm creating a CRUD-based web project, and am thinking about using a server side MVC framework (such as CodeIgniter or Laravel) in tandem with a client side MVC framework (such as AngularJS). Is this a fairly common approach? After all, it's clear that I need something on the server, and that doing MVC on the client as well can enhance my application. But I feel that two MVC frameworks on the same project would just get in the way of each other and lead to disproportionate complexity and repetition.

What kind of approach or architecture would help me get the best out of both MVC frameworks when using one on the client, the other on the server?

答:
Laravel and AngularJS actually work quite well together; there's a good video on Laracasts about it and a few good articles online.

In general you wouldn't want to use multiple MVC frameworks in one project as it increases bloat, as well as a lot of redundancy. Your average PHP MVC framework will include an ORM, Templating engine, router and so on - components that you only need one of. In fact, using two will most likely increase complexity and introduce conflicts.

The exception here is where frameworks are separated clearly, like in the case of a server side framework and a client side framework. Both frameworks are actually doing completely different things.

However, if you want to combine the use of Laravel and AngularJS then you most likely wouldn't be using all of Laravel's features. The recommended strategy is to implement something akin to a REST API using Laravel's Resource routes - and to treat all interactions as AJAX API calls.

This means you won't really be using the V of Laravel; I.e Views with Blade. (Apart from perhaps the layout for initially loading the app)

A quick google of "Laravel and AngularJS" returns a whole plethora of articles, but perhaps the best resource is this sample project:

Github example: https://github.com/bktz/Laravel-4-AngularJS-Starter-Site

A noteworthy article was this one though:

http://scotch.io/tutorials/php/create-a-laravel-and-angular-single-page-comment-application

It discusses the proposed structure of such an app, as well as the resource routes I mentioned above.


问:
Using JDBC to asynchronously read large Oracle table
What strategies can be used to read every row in a large Oracle table, only once, but as fast as possible with JDBC & Java ?

Consider that each row has non-trivial amounts of data (30 columns, including large text in some columns).

Some strategies I can think of are:

Single thread and read table.  (Too slow, but listed for clarity)

Read the id's into ConcurrentLinkedQueue, use threads to consume queue and query by id in batches.

Read id's into a JMS queue, use workers to consume queue and query by id in batches.

What other strategies could be used ?

For the purpose of this question assume processing of rows to be free.

答:
First thing is how fast do you need it to be? One should be mindful to not get into the "premature optimization" zone.

The first suggestion for clarity is to increase the jdbc_batch_size. If your oracle database sits on a different host then you will see an increase in performance on all your suggestions.

You can implement paging to split your dataset into multiple pages, then using your suggestions

Read the entire row/page into a ConcurrentLinkedQueue, use threads to consume queue (you avoid having to re-query based on id at the expense of using more memory)

A similar approach can be taken for the JMS suggestion

Another suggestion, although I am not sure whether this will work, is to use the Java Streams API and process the ResultSet. The code for this will probably be more concise so that would be a plus. The only downside is that you might not get ResultSet to process in parallel (see this and this for some insight).


问:
Keeping test and release version numbers in sync
I'm currently beta-testing an iPhone app. Right now I have sent out the first beta-test for my users and I have labeled that release as 1.0 for my testers.

Now since the testers have tested the app we have discovered some bugs that I have fixed and I'm ready to send out a new beta-test for my users. Should I label the release as 1.0.1 then?

Another question related to this is, when my testers have tested this 1.0.1 release and they do not find any bugs it would be a good time to release this version to the public in the App Store. What version number should I release this under in the App Store? First thought is that since it's the first release to the App Store it should have version number 1.0 but then it will be "out of sync" with the version that has been tested (1.0.1).

答:
One solution that is working for me is to increment the build field (CFBundleVersion) every time we make an internal release to the QA team, and leaving the Version field (CFBundleShortVersionString) with what we call 'marketing version' and we let the business team to decide what the value will be.

In your example we will first release to the beta users with version 1.0 and build 1. After receiving the feedback and fixing some issues we will be releasing to the beta team a new build with the version still at 1.0 but the build now will be 2.
After we release on Apple Store we will be sending the releases to the beta users with version 1.0.1 (or 1.5, or 2.0, whatever we decide is the next target) and with build 3, always incrementing the build number on every release.

This works well because TestFlight shows the build next to the version, i.e. 1.0 (2), and we put the version and build number on an about box inside our app.


问:
Manage ClickOnce releases for different parties
I'm struggling with release management of a piece of software. First some general information:

It is a ClickOnce application

I follow the release often practice

There are about 30 parties served with this software

I need full control which update will be delivered to which party

Not each party is allowed to get the latest update/release

Each party has multiple clients that are all allowed to get the latest update, served for the specific party

So that's what my requirements are in a rough description. So let me explain what I was thinking about how to solve this.

I would like to create a "deployment" website (asp.net) that will handle all the requests

There are two endpoints one for download the client and one where the client checks for updates

So each party has a separate endpoint like DeploymentSite/party1 and another for DeploymentSite/party2

The Application Files should still be stored centralized

So I thought it would be manageable with mage.exe with the following steps

Build application and store new release into Application Files Repository/Folder

Get parties that should be updated (config file, database what ever)

Run mage.exe to create a new application and deployment manifest for each party in the update list with new Application File Location (1.0.2)

Actually I'm really struggling with this mage.exe staff. I can't create the appropriate files with the needed codebase.

How to handle thes requirements?

答:
The web site sounds like the right approach for the application deployment and checking for updates. You could investigate a C# MVC site for this approach.

I thought I could help more with the building of all the manifest files. My company creates a piece of software called ClickOnceMore which is designed to help integrate ClickOnce into a build cycle. I think it would be perfect for your scenario to help with the multiple clients.

ClickOnceMore has a concept of macros. To implement your different parties, you would create a single ClickOnceMore package with all of the files needed for the application and then add a macro set for each client. For the config files you can reference a different one for each client using a macro value, you can also reference a different output location for each client. When you build from the command line you can specify which macro set to use.

I hope this helps. There is a free trial of ClickOnceMore available from our website.


问:
open source social network allowing advertising
I want to build up a social network, targeted to a specific interest. I want to generate revenues in form of ads. I first thought of building it from scratch, which will take a lot of time (even if it's something simple), then i remembered there are open source options like Diaspora or Friendica. I don't know if there are others... My question is, with these previously mentioned projects or any other, ¿is it possible to legally generate revenues?

Diaspora license is: AGPLv3,[3][4] some parts dual-licensed under MIT License[5] as well

Friendica: AGPL

¡Thank you!

答:
Both the AGPL and the MIT license only address redistribution and have no restrictions at all regarding how you use the software. Neither forbids any form of commercial activity.

The only restriction is that the AGPL forces you to publish any code changes you make. So when you change the software to add support for displaying advertisement, you will have to publish these changes.


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
Because

Programming is becoming (if not already) a commodity skill and competition is cut throat. That makes pay rate

To make serious money you need to keep in touch with the bleeding edge of technology these days and that means a lot of investment into yourself. Most people by nature are loathe to make such efforts. In good old times, C++ or COBOL alone would have fetched you 30-50$/hr if not more, these days you need a lot (hell lot really) more than that. How many people do you know who are learning GPGPU with C++ or a distributed source control like Git just to stay ahead of the curve?

Industries by themselves are penny pinching, making do with limited developer pool to do extra work which could earlier be contracted out


问:
Design for reusable java module which uses DB connections
I'm tasked with changing some procedural Java code into Object Oriented re-usable module. It's an XML generator utility which uses velocity for XML generation. There are also business rule enrichments, all of which is configurable in Database tables. I have already removed huge if-else statements for rules and made them into Rule Objects with Abstract classes and interfaces which other Applications can extend and implement. However I'm facing difficulty with re-designing the overall class - XMLGeneratorUtil, which takes a JDBC connection , Logger and Properties in its constructor and does a hell lot of things in the constructor like building different Data structures(containing static data) from database.

Now, I know its not good to connect to Database from Constructor, but if I change to some thing like below:

```<code>XMlGeneratorUtil xmlUtil = new XMLGeneratorUtil();
xmlUtil.initialize(Conenriches conn, Properties prop , Logger logger) // Do DB Connections and all initializations here
xmlUtil.generateXML(data); // Data is a HashMap containing busines data that goes into the XML
</code>```

How can I be sure that the users of my utility call initialize before they call generateXML? Should I create some Wrapper that internally creates a lightweight object and then initializes it without the user knowing it?

Also , is it good for my re-usable library to accept Connection as a parameter? Idea is that the calling Application of my utility may choose to manage their own Connection , so they just pass it to my API

Against the SRP (Single Responsibility principle) the XMLGeneratorUtil manipulates business data(which ultimately goes into XML data) as well as generates XML. Should the data enrichment be exposed as different API? (And then the user calls XMLGeneratorUtil)

答:
Answers to your points:

How can I be sure that the users of my utility call initialize before they call generateXML? Should I create some Wrapper that internally creates a lightweight object and then initializes it without the user knowing it?

No.  That would essentially be the same thing as invoking the database from your constructor.  Instead, make generateXML throw an exception if the object is in the wrong state (eg, initialize hasnt' been called).

Also , is it good for my re-usable library to accept Connection as a parameter? Idea is that the calling Application of my utility may choose to manage their own Connection , so they just pass it to my API

Probably not.  Consider injecting something a bit less low-level.  Surely the Rules Object's dependency isn't the entire database, but simply a subset of its data.  Could that subset be represented as a Repository?  In other words, if your Rules Object requires pulling rules from the database, don't hand it a dbConnection, hand it a RulesRepository.

I can't answer the third question because I'm not sure what you mean by "enriches business data."

But, at a high level, the answer to this question is:

Rethink your object dependencies.  Injecting a database connection is very broad and allows your Rules Object to do far more with your data that it should be able to.

Consider injecting classes that only expose what is needed from the database.  Using a Repository will help you do this and will also decouple you from the data persistence medium.  So, in the unlikely event you ditch databases and move to another storage medium, you'll only need to update your Repositories and not all their consumers.


问:
Interfaces and abstraction: takes more time?
At the company I work for I want to improve the way we write software: designing our applications more SOLID. We've been in a new project for a few weeks and I've tried to apply some good practices in its design. For example, loose coupling by programming against interface instead of a concrete class, dependency injection / inversion of control, seperation of concerns etc. This is all meant as a springboard to test driven development in the (far) future.

In the application we're developing we need to calculate a score depending on a filled in survey by a user (a survey has categories which themselves have questions / answers). I've splitted the calculations in multiple classes and subsequent interfaces (calculating score of a question, category, survey, etc).

Also, in the front-end (ASP.NET Web Forms), I've splitted many parts of pages into seperate user controls. For example: a 'widget' which shows the culumative scores in the application or a widget for showing all files related to the application. These are all seperate user controls.

We're now a few weeks in the project and I find that some of my co-workers (especially ones older of age) are complaining about:

Not being able to find a implementation of a interface directly but needing to 'search' for the implementation

Needing more time to find the implementation of a particular markup on the front-page

They also don't see the point of splitting up seperate functionality into user controls because sometimes (usually) the user control is only used on one page. I, on the opposite, find it to work better since it keeps the code-behind of a page tight and lean.

My question is: Do I apply good practices the wrong way or does it simply take time to get used to it?

Note: Until very recently we developed software with tight coupling (e.g: static classes, never use interfaces, only use user control when necessary).

答:
A few things to keep in mind:

"Splitting" and "separating" code does a few things. Two of them: it disperses knowledge that once  was concentrated (and could be read and understood in a single look or a few looks) and increases the vocabulary (sometimes, dramatically). With this in mind, don't "follow" "principles". One, they have very short limits. Two, many people take "following" as a good substitute for awareness and intelligence -- however, nothing beats looking honestly what is going on and analyzing it in all aspects. But by all means, test those limits if you can, make it clear the suggestion of exploring approaches to tackle existing problems (and have always a SOLID -- not the "principle" -- case for justifying the existence of these problems linked with the priorities of the project), and if your team is willing, there is a lot to learn doing so.

You mentioned classes and interfaces. I take you are using a language with poor instruments to do what you intent. This probably intensifies the previous bullet, specially regarding to the increase of "vocabulary". Its side effects include "people who once were fluent, are not fluent anymore", "it takes more effort to get fluent", and "it takes more effort to say what I mean". There is more to say about this instead of metaphors in quotes, but lets just conclude this naturally goes against human mood. And happy programmers are better at solving problems (warning: link to empirical research).

Both bullets of complains you mentioned are legit. And what you are aiming at (as far as finding a proper design and methodology) is also legit.

Also, food for thought: code identified with poor quality to one's eye is deceiving (specially regarding a foggy concept of "quality"). For instance, "local messes" (ie, confined to a procedure) which are uniform and easy to read (regardless if it irritates the eyes of a mind attached to a certain way of organizing things) imposes very little risk to the project, usually have 0 global influence in the design of the system given its local isolation (and, say, code is reentrant and pure / have no external side effects) and may be much more welcoming to changes. The same code refactored and separated, often times make it more difficult to read, understand and tackle, because the number of "moving parts" increased and it is not clear, from looking at a list of methods, what is the relationship of them, who is the entry point, how they cooperate, etc.

Regarding the last point, it's very common to see people going all the way with this separation (the reasons change with time but today it is done in the name of "making it easy to write unit tests"). At the same time, some of them frequently overlook the end result -- they notice the degenerated trash it became, they hesitate, you see their heads thinking "this is not..what I expected", but they insist on it; after all they followed "best practices", right? And if the result was pleasing with a previous refactored piece code, this refactored code should be pleasing too, right?....even though it is not. Frustrated, many start acting like a pendulum, and go to the opposite direction writing crap code with no thinking behind it and everything, but I digress.

So, concluding:

Choosing what to separate, how to separate and when to separate is considerably more important (specially, more important than any current notion of aesthetics. If the claim is "easy to change", it should be backed up by the risk of a certain section of code to be subjected to change, and how much or how little a design contribute to its overall economy $). In other words, this is not something that should always be done, and the result will always be good and profitable with no risk of making things worse. So constant evaluation and assessment of benefits, risks and trade offs precedes these practices.

If "separating" is silver (and an impure kind), "synthesizing" is gold.


问:
Optimization ended up in casting an object at each method call
I've been doing some optimization for the following piece of code :

```<code>public void DrawLine(int x1, int y1, int x2, int y2, int color)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color);
}
</code>```

After profiling it about 70% of the time spent was in getting a context for drawing and disposing it.

I ended up sketching the following overload :

```<code>public void DrawLine(int x1, int y1, int x2, int y2, int color, BitmapContext bitmapContext)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, bitmapContext);
}
</code>```

Until here no problems, all the user has to do is to pass a context and performance is really great as a context is created/disposed one time only (previously it was a thousand times per second).

The next step was to make it generic in the sense it doesn't depend on a particular framework for rendering (besides .NET obvisouly).

So I wrote this method :

```<code>public void DrawLine(int x1, int y1, int x2, int y2, int color, IDisposable bitmapContext)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, (BitmapContext)bitmapContext);
}
</code>```

Now every time a line is drawn the generic context is casted, this was unexpected for me.

Are there any approaches for fixing this design issue ?

Note :

_bitmap is a WriteableBitmap from WPF

BitmapContext is from WriteableBitmapEx library

DrawLineBresenham is an extension method from WriteableBitmapEx

答:
I fixed it by doing the following : 2 methods like in OpenGL to call before/after drawing operations.

```<code>public void RenderBegin()
{
    _context = _bitmap.GetBitmapContext();
}

public void RenderEnd()
{
    _context.Dispose();
}
</code>```

No need for an extra DrawLine overload and obviously the method uses the context every time.

But no more ugly cast at every call :D

Body:
I fixed it by doing the following : 2 methods like in OpenGL to call before/after drawing operations.

public void RenderBegin()
{
    _context = _bitmap.GetBitmapContext();
}

public void RenderEnd()
{
    _context.Dispose();
}

No need for an extra DrawLine overload and obviously the method uses the context every time.

But no more ugly cast at every call :D


答: I would implement it so context is created when DrawLine is called for the first time and make the whole class IDisposable and dispose the context in there, it if was created of course.

Title: Optimization ended up in casting an object at each method call

Body:
I've been doing some optimization for the following piece of code :

```<code>public void DrawLine(int x1, int y1, int x2, int y2, int color)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color);
}
</code>```

After profiling it about 70% of the time spent was in getting a context for drawing and disposing it.

I ended up sketching the following overload :

```<code>public void DrawLine(int x1, int y1, int x2, int y2, int color, BitmapContext bitmapContext)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, bitmapContext);
}
</code>```

Until here no problems, all the user has to do is to pass a context and performance is really great as a context is created/disposed one time only (previously it was a thousand times per second).

The next step was to make it generic in the sense it doesn't depend on a particular framework for rendering (besides .NET obvisouly).

So I wrote this method :

```<code>public void DrawLine(int x1, int y1, int x2, int y2, int color, IDisposable bitmapContext)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, (BitmapContext)bitmapContext);
}
</code>```

Now every time a line is drawn the generic context is casted, this was unexpected for me.

Are there any approaches for fixing this design issue ?

Note :

_bitmap is a WriteableBitmap from WPF

BitmapContext is from WriteableBitmapEx library

DrawLineBresenham is an extension method from WriteableBitmapEx


答:
Your first paragraph sounds like a case of cargo cult software engineering. Just because you are creating interfaces and using DI is not going to create a good program design. Just ask yourself: How many interface have only one concrete class as implementation? People having to look for implementation of an interface is clear indication there is something wrong. In many cases, interfaces might really be unneeded abstraction for your current business case and it just complicates the design.

One thing that raises red flag is this line:

This is all meant as a springboard to test driven development in the (far) future.

There is so much wrong with this kind of thinking. If you want to do TDD, do it from very beginning. First, having classes as interfaces doesn't make them testable. Especially if you are looking for tests that actually make sense and are not maintenance nightmare. TDD is meant as a way to ensure your code is divided in logical parts, that are logical to test. If, for example, you would have problems figuring how to test specific functionality, then it would be clear indication the code design is wrong. There is high chance, that even with your code, it will become problematic to create unit tests for it. TDD can also help against unneeded abstraction I mentioned above, because the class design will be only complex enough to fulfill all needed requirements, but not more. Here is nice example.

As for the mentality of others against TDD: Those are extremely common counter-arguments and stem from misunderstanding of TDD and there are even studies that say TDD improves quality of code, thus reducing defects and maintenance cost. All for 15-35% increase in initial development, which is negligible compared to time you save by reducing maintenance cost.

To sum it up. I would heavily recommend you to stop worrying about SOLID and learn something about OOP design and how to apply TDD.

Title: Interfaces and abstraction: takes more time?

Body:
At the company I work for I want to improve the way we write software: designing our applications more SOLID. We've been in a new project for a few weeks and I've tried to apply some good practices in its design. For example, loose coupling by programming against interface instead of a concrete class, dependency injection / inversion of control, seperation of concerns etc. This is all meant as a springboard to test driven development in the (far) future.

In the application we're developing we need to calculate a score depending on a filled in survey by a user (a survey has categories which themselves have questions / answers). I've splitted the calculations in multiple classes and subsequent interfaces (calculating score of a question, category, survey, etc).

Also, in the front-end (ASP.NET Web Forms), I've splitted many parts of pages into seperate user controls. For example: a 'widget' which shows the culumative scores in the application or a widget for showing all files related to the application. These are all seperate user controls.

We're now a few weeks in the project and I find that some of my co-workers (especially ones older of age) are complaining about:

Not being able to find a implementation of a interface directly but needing to 'search' for the implementation

Needing more time to find the implementation of a particular markup on the front-page

They also don't see the point of splitting up seperate functionality into user controls because sometimes (usually) the user control is only used on one page. I, on the opposite, find it to work better since it keeps the code-behind of a page tight and lean.

My question is: Do I apply good practices the wrong way or does it simply take time to get used to it?

Note: Until very recently we developed software with tight coupling (e.g: static classes, never use interfaces, only use user control when necessary).


问:
selling closed source commercial product in a virtualbox (GPL)
Can I sell a closed source commercial product inside a virtualbox VM?

This is extremely useful when you want to deliver server side software to users, and not mess in with different OS's (windows/osx).

By reading some of the answers here in programmers, I get that it should not be a problem since my software does not link a GPL library, and that's practically the biggest concern of GPL FOSS.

So, if I use GPL software just bundled with Closed source software that's fine?

答:
Probably not.

Please read the licence for virtualbox and make your own decision. If you don't understand it, then perhaps you should pay a lawyer to read it for you. Since virtualbox is owned by Oracle you could write and ask them.

With most open source licences you can do what you like with the code as long as it's for your own personal use. However if you plan on distributing the code (or any significant part of it) to others then you can only do that in the way that the licence allows.

So if you're going to distribute virtualbox you have to comply with its licence. It's GPL (not LGPL) and that most likely means you have to release full source code.

As I tell people repeatedly, if you make no money out of it and harm no-one then just do your best, acknowledge the work of others and don't worry too much. If you make money out of your product or services and/or if you may cause damage to someone, you must take competent legal advice. That won't protect you, but it will warn you about the risks and possibly help to mitigate them. You do not want to be having this conversation with Oracle's lawyers after the event.


问:
Do you actively think about security when coding?
When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>

答:
It should be something any developer builds in to the process from the ground up to a greater or lesser degree, depending on application etc. Unfortunately, as devs don't tend to quote for security, buyers don't tend to think of it (I know, this is a bit catch-22, because if the buyers want the cheapest quote, it maybe won't include security)

As a developer you can gain a definite advantage if you are skilled in this area - I'm specifically thinking about banks and financial services, but other industries are also applicable. Currently they may budget 70 - 100k in training for a new graduate to be brought up to speed on processes, security and other specifics to that organisation. If you can save them 30k of that, that's a good CV plus!

In the UK, the Institute of Information Security Professionals, and in Scotland, the Centre of Excellence in Security and Cybercrime are working closely with Universities to help review course materials, provide guest lectures on real world implications of poor coding and facilitating summer placements (eg software developers placed into fraud divisions in law enforcement.) Most of the supporting organisations are doing this for free, as it has the potential to save them a large amount of money - sounds like value to me.

(disclaimer - I have been security guy for various global organisations)


答: Why not make the whole constructor-building into a class and pass only that class into the constructor? Then you can even abstract it as interface, so the XML generation doesn't even depend on DB and can accept any data.</p>

Title: Design for reusable java module which uses DB connections

Body:
I'm tasked with changing some procedural Java code into Object Oriented re-usable module. It's an XML generator utility which uses velocity for XML generation. There are also business rule enrichments, all of which is configurable in Database tables. I have already removed huge if-else statements for rules and made them into Rule Objects with Abstract classes and interfaces which other Applications can extend and implement. However I'm facing difficulty with re-designing the overall class - XMLGeneratorUtil, which takes a JDBC connection , Logger and Properties in its constructor and does a hell lot of things in the constructor like building different Data structures(containing static data) from database.

Now, I know its not good to connect to Database from Constructor, but if I change to some thing like below:

```<code>XMlGeneratorUtil xmlUtil = new XMLGeneratorUtil();
xmlUtil.initialize(Conenriches conn, Properties prop , Logger logger) // Do DB Connections and all initializations here
xmlUtil.generateXML(data); // Data is a HashMap containing busines data that goes into the XML
</code>```

How can I be sure that the users of my utility call initialize before they call generateXML? Should I create some Wrapper that internally creates a lightweight object and then initializes it without the user knowing it?

Also , is it good for my re-usable library to accept Connection as a parameter? Idea is that the calling Application of my utility may choose to manage their own Connection , so they just pass it to my API

Against the SRP (Single Responsibility principle) the XMLGeneratorUtil manipulates business data(which ultimately goes into XML data) as well as generates XML. Should the data enrichment be exposed as different API? (And then the user calls XMLGeneratorUtil)


问:
Why a function returning by address can not be a lvalue?
Why is it not possible to set a function returning an address while it is possible to set a function that returns a reference.</p>

```<code>int* returnByAddress()
{
    int x = 20;
    return &x;
}

int& returnByReference()
{
    int x = 30;
    return x;
}

int main()
{
    returnByReference() = 23; // possible
    int x = 23;
    returnByAddress() = &x;   // not a lvalue error
    *returnByAddress() = 245; // possible

    return 0;
}
</code>```

答:
To start off, your code is broken. Returning a reference or the address of a local variable is returning garbage. Never do this. Here I've rewritten your example to return something real.

```<code>int xByAddress = 20;
int xByReference = 30;

int* returnByAddress()
{
    return &xByAddress;
}

int& returnByReference()
{
    return xByReference;
}

int main()
{
    returnByReference() = 23; //possible
    int x = 23;
    returnByAddress() = &x; //not a lvalue error
    *returnByAddress() = 245; //possible

    return 0;
}
</code>```

In this example, xByReference is assigned the value 23. xByAddress is assigned the value 245. Of course, returnByAddress() = &x; is invalid.

The rule is: functions return rvalues. The only way around this is to return a reference.

returnByAddress() returns a pointer by rvalue. You can deference the pointer to get an lvalue of the thing pointed at.

Following this rule, you can return a reference to the pointer.

```<code>int xByAddress = 20;
int *xPointer = nullptr;

int*& returnByPointerReference()
{
    xPointer = &xByAddress;
    return xPointer;
}

int main()
{
    int x = 23;
    returnByPointerReference() = &x; //not a lvalue error
    return 0;
}
</code>```

This code changes xPointer to point at the address of x.

Body:
To start off, your code is broken. Returning a reference or the address of a local variable is returning garbage. Never do this. Here I've rewritten your example to return something real.

int xByAddress = 20;
int xByReference = 30;

int* returnByAddress()
{
    return &xByAddress;
}

int& returnByReference()
{
    return xByReference;
}

int main()
{
    returnByReference() = 23; //possible
    int x = 23;
    returnByAddress() = &x; //not a lvalue error
    *returnByAddress() = 245; //possible

    return 0;
}

In this example, xByReference is assigned the value 23. xByAddress is assigned the value 245. Of course, returnByAddress() = &x; is invalid.

The rule is: functions return rvalues. The only way around this is to return a reference.

returnByAddress() returns a pointer by rvalue. You can deference the pointer to get an lvalue of the thing pointed at.

Following this rule, you can return a reference to the pointer.

int xByAddress = 20;
int *xPointer = nullptr;

int*& returnByPointerReference()
{
    xPointer = &xByAddress;
    return xPointer;
}

int main()
{
    int x = 23;
    returnByPointerReference() = &x; //not a lvalue error
    return 0;
}

This code changes xPointer to point at the address of x.


答:
Not that I'm an expert, but you could use a corpora like google does, and just use the statistics of words that are found in the internet.

For example, if there are 100K occurrences of Wallmart in the WWW and only 10K "wall mart" you would know that it's probably best to use the first one.

Title: Are there any algorithms for splitting or combining words into their more common form?

Body:
Are there any existing algorithms which can look through a list of words and split or combine words into their more common form?

For example, I have a list of many business names in the health care industry. The word "healthcare" is often written "health care". There are also business names which might be split or combined, such as "Walmart" and "Wal mart".

Are there any algorithms which can look at my list of words and identify that "healthcare" is more often written as two words, and that "Wal mart" is more often written as a single word?

I'm looking for the names of existing algorithms (which can help when searching the web), or links to existing white-papers or blog posts.

I'd prefer an algorithm that doesn't depend on a dictionary or other external list of words or business names.

EDITS:

Background:

I already have some code that is moderately successful at this task. The code was thrown together without much rigor. I hoped there were some established algorithms, which would likely be more academic and complete then what I've come up with. This question is not about the method I've come up with, but saying "it's impossible" doesn't convince me.

Clarification:

The "more common form" of a word is the way the word(s) are most often written. For example, "Walmart" appeared many times, and "Wal mart" appeared many times, but "Walmart" appeared more often then "Wal mart" and so "Walmart" is the "more common form" of the word.

I don't expect this algorithm to produce perfect results. Like any machine learning problem, I expect the results to be dependent on the quality of data I give it, and how much data I have.


答:
What David Everlöf said in the comment is actually not a too bad suggestion.
More generally, if your application has internet access, it may be a good idea to see if you can make it consult online resources.

To stick with google, it is not hard to send a http request which performs a google search on the word you are examining.
Then extract the suggestion part ('did you mean: Wallmart?') from the html document that is returned (if existent) and correct your word based on that suggestion.


问:
Randomized Hash function with no collisions
Related to the question Which hashing algorithm is best for uniqueness and speed?

Is there a way to create a hash function, or find one, whose hash length depends completely on the input length, has an adjustable hash character set (Since it must be 1-to-1 function the input must comply to this character set constraint as well).

Moreover the most important part is that the hash function generates as random as possible strings. So for example it would be possible to get the following two different results.

```<code>Hash(aaaa)->blue // for character set a-z
</code>```

and

```<code>Hash(aaaz)->pink  // for character set a-z
</code>```

More examples:

```<code>Hash(aa@12a)->dakj@4   // for character set a-z, @, 0-9
</code>```

and

```<code>Hash(a2#46Ww)->@3#0Pdw // for character set a-z A-Z, !-), 0-9
</code>```

Notice
the character length between input and output and the character sets.

What I thought so far was a probability distribution function, there are random distribution functions but I am not sure how to get there.

http://en.wikipedia.org/wiki/Probability_distribution

http://en.wikipedia.org/wiki/Normal_distribution

答:
This is not a hash function.  It's either an encoding function or an encryption function.

Usually when I've encountered a problem of this form, it is because I have some sort of IDs that I want to "look" random.  Assuming I don't care about security, I'll normally create an algorithm which works as follows:

Map my data to numbers (usually, by treating a string in a character set containing X characters as a baseX number).

Map my numbers to new numbers.  Eric Lippert suggests using Multiplicative Inverses for this purpose.  Skip32 encoding (AKA Skip32 encryption, but it's not secure) also works for this purpose.

Reverse the mapping in step 1.

To decode, perform the same steps in reverse.


问:
Why are interfaces more helpful than superclasses in achieving loose coupling?
(For the purpose of this question, when I say 'interface' I mean the language construct interface, and not an 'interface' in the other sense of the word, i.e. the public methods a class offers the outside world in order to communicate with and manipulate it.)

Loose coupling can be achieved by having an object depend on an abstraction instead of a concrete type.

This allows for loose coupling for two main reasons: 1- abstractions are less likely to change than concrete types, which means the dependent code is less likely to break. 2- different concrete types can be used at runtime, because they all fit the abstraction. New concrete types can also be added later with no need to alter the existing dependent code.

For example, consider a class Car and two subclasses Volvo and Mazda.

If your code depends on a Car, it can use either a Volvo or a Mazda during runtime. Also later on additional subclasses could be added with no need to change the dependent code.

Also, Car - which is an abstraction - is less likely to change than Volvo or Mazda. Cars have been generally the same for quite some time, but Volvos and Mazdas are far more likely to change. I.e. abstractions are more stable than concrete types.

All of this was to show that I understand what loose coupling is and how it is achieved by depending on abstractions and not on concretions. (If I wrote something inaccurate please say so).

What I don't understand is this:

Abstractions can be superclasses or interfaces.

If so, why are interfaces specifically praised for their ability to allow loose coupling? I don't see how it's different than using a superclass.

The only differences I see are: 1- Interfaces aren't limited by single inheritance, but that doesn't have much to do with the topic of loose coupling. 2- Interfaces are more 'abstract' since they have no implementation logic at all. But still, I don't see why that makes such a big difference.

Please explain to me why interfaces are said to be great in allowing loose coupling, while simple superclasses are not.

答:
There is coupling between parent and child classes, since the child depends on the parent.

Say we have a class A, and class B inherits from it.  If we go into class A and change things, class B gets changed too.

Say we have an interface I, and class B implements it.  If we change interface I, then although class B might not implement it anymore, class B is unchanged.


答:
Terminology: I'll refer to the language construct interface as interface, and to the interface of a type or object as surface (for a lack of a better term).

Loose coupling can be achieved by having an object depend on an abstraction instead of a concrete type.

Correct.

This allows for loose coupling for two main reasons: 1- abstractions are less likely to change than concrete types, which means the dependent code is less likely to break. 2- different concrete types can be used at runtime, because they all fit the abstraction. New concrete types can also be added later with no need to alter the existing dependent code.

Not quite correct. Current languages do not generally anticipate that an abstraction will change (although there are some design patterns to handle that). Separating specifics from general things is abstraction. This is usually done by some layer of abstraction. This layer can be changed to some other specifics without breaking code that builds upon this abstraction – loose coupling is achieved. Non-OOP example: A sort routine might be changed from Quicksort in version 1 to Tim Sort in version 2. Code that only depends on the result being sorted (i.e. builds upon the sort abstraction) is therefore decoupled from the actual sorting implementation.

What I termed surface above is the general part of an abstraction. It now happens in OOP that one object must sometimes support multiple abstractions. A not-quite optimal example: Java's java.util.LinkedList supports both the List interface which is about the “ordered, indexable collection” abstraction, and supports the Queue interface which (in rough terms) is about the “FIFO” abstraction.

How can an object support multiple abstractions?

C++ doesn't have interfaces, but it has multiple inheritance, virtual methods, and abstract classes. An abstraction can then be defined as an abstract class (i.e. a class that cannot be immediately instantiated) that declares, but not defines virtual methods. Classes that implement the specifics of an abstraction can then inherit from that abstract class and implement the required virtual methods.

The problem here is that multiple inheritance can lead to the diamond problem, where the order in which classes are searched for a method implementation (MRO: method resolution order) can lead to “contradictions”. There are two responses to this:

Define a sane order and reject those orders that can't be sensibly linearized. The C3 MRO is fairly sensible and works well. It was published 1996.

Take the easy route and reject multiple inheritance throughout.

Java took the latter option and chose single behavioral inheritance. However, we still need the ability of an object to support multiple abstractions. Therefore, interfaces have to be used which do not support method definitions, only declarations.

The result is that the MRO is obvious (just look at each superclass in order), and that our object can have multiple surfaces for any number of abstractions.

This turns out to be rather unsatisfactory, because quite often a bit of behavior is part of the surface. Consider an Comparable interface:

interface Comparable<T> {
    public int cmp(T that);
    public boolean lt(T that);  // less than
    public boolean le(T that);  // less than or equal
    public boolean eq(T that);  // equal
    public boolean ne(T that);  // not equal
    public boolean ge(T that);  // greater than or equal
    public boolean gt(T that);  // greater than
}
```

<p>This is very user-friendly (a nice API with many convenient methods), but tedious to implement. We would like the interface to only include <code>cmp</code>, and implement the other methods automatically in terms of that one required method. Mixins, but more importantly Traits [1],[ 2] solve this problem without falling into the traps of multiple inheritance.</p>

<p>This is done by defining a trait composition so that the traits don't actually end up taking part in the MRO – instead the defined methods are composed into the implementing class.</p>

<p>The <code>Comparable</code> interface could be expressed in Scala as</p>

<pre class="lang-scala prettyprint-override"><code>trait Comparable[T] {
    def cmp(that: T): Int
    def lt(that: T): Boolean = this.cmp(that) <  0
    def le(that: T): Boolean = this.cmp(that) <= 0
    ...
}
</code>```

When a class then uses that trait, the other methods get added to the class definition:

// "extends" isn't different from Java's "implements" in this case
case class Inty(val x: Int) extends Comparable[Inty] {
    override def cmp(that: Inty) = this.x - that.x
    // lt etc. get added automatically
}
```

So Inty(4) cmp Inty(6) would be -2 and Inty(4) lt Inty(6) would be true.

Many languages have some support for traits, and any language that has a “Metaobject Protocol (MOP)” can have traits added to it. The recent Java 8 update added default methods which are similar to traits (methods in interfaces can have fallback implementations so that it's optional for implementing classes to implement these methods).

Unfortunately, traits are a fairly recent invention (2002), and are thus fairly rare in the larger mainstream languages.

Title: Why are interfaces more helpful than superclasses in achieving loose coupling?

Body:
(For the purpose of this question, when I say 'interface' I mean the language construct interface, and not an 'interface' in the other sense of the word, i.e. the public methods a class offers the outside world in order to communicate with and manipulate it.)

Loose coupling can be achieved by having an object depend on an abstraction instead of a concrete type.

This allows for loose coupling for two main reasons: 1- abstractions are less likely to change than concrete types, which means the dependent code is less likely to break. 2- different concrete types can be used at runtime, because they all fit the abstraction. New concrete types can also be added later with no need to alter the existing dependent code.

For example, consider a class Car and two subclasses Volvo and Mazda.

If your code depends on a Car, it can use either a Volvo or a Mazda during runtime. Also later on additional subclasses could be added with no need to change the dependent code.

Also, Car - which is an abstraction - is less likely to change than Volvo or Mazda. Cars have been generally the same for quite some time, but Volvos and Mazdas are far more likely to change. I.e. abstractions are more stable than concrete types.

All of this was to show that I understand what loose coupling is and how it is achieved by depending on abstractions and not on concretions. (If I wrote something inaccurate please say so).

What I don't understand is this:

Abstractions can be superclasses or interfaces.

If so, why are interfaces specifically praised for their ability to allow loose coupling? I don't see how it's different than using a superclass.

The only differences I see are: 1- Interfaces aren't limited by single inheritance, but that doesn't have much to do with the topic of loose coupling. 2- Interfaces are more 'abstract' since they have no implementation logic at all. But still, I don't see why that makes such a big difference.

Please explain to me why interfaces are said to be great in allowing loose coupling, while simple superclasses are not.

Body:
Terminology: I'll refer to the language construct interface as interface, and to the interface of a type or object as surface (for a lack of a better term).

Loose coupling can be achieved by having an object depend on an abstraction instead of a concrete type.

Correct.

This allows for loose coupling for two main reasons: 1- abstractions are less likely to change than concrete types, which means the dependent code is less likely to break. 2- different concrete types can be used at runtime, because they all fit the abstraction. New concrete types can also be added later with no need to alter the existing dependent code.

Not quite correct. Current languages do not generally anticipate that an abstraction will change (although there are some design patterns to handle that). Separating specifics from general things is abstraction. This is usually done by some layer of abstraction. This layer can be changed to some other specifics without breaking code that builds upon this abstraction – loose coupling is achieved. Non-OOP example: A sort routine might be changed from Quicksort in version 1 to Tim Sort in version 2. Code that only depends on the result being sorted (i.e. builds upon the sort abstraction) is therefore decoupled from the actual sorting implementation.

What I termed surface above is the general part of an abstraction. It now happens in OOP that one object must sometimes support multiple abstractions. A not-quite optimal example: Java's java.util.LinkedList supports both the List interface which is about the “ordered, indexable collection” abstraction, and supports the Queue interface which (in rough terms) is about the “FIFO” abstraction.

How can an object support multiple abstractions?

C++ doesn't have interfaces, but it has multiple inheritance, virtual methods, and abstract classes. An abstraction can then be defined as an abstract class (i.e. a class that cannot be immediately instantiated) that declares, but not defines virtual methods. Classes that implement the specifics of an abstraction can then inherit from that abstract class and implement the required virtual methods.

The problem here is that multiple inheritance can lead to the diamond problem, where the order in which classes are searched for a method implementation (MRO: method resolution order) can lead to “contradictions”. There are two responses to this:

Define a sane order and reject those orders that can't be sensibly linearized. The C3 MRO is fairly sensible and works well. It was published 1996.

Take the easy route and reject multiple inheritance throughout.

Java took the latter option and chose single behavioral inheritance. However, we still need the ability of an object to support multiple abstractions. Therefore, interfaces have to be used which do not support method definitions, only declarations.

The result is that the MRO is obvious (just look at each superclass in order), and that our object can have multiple surfaces for any number of abstractions.

This turns out to be rather unsatisfactory, because quite often a bit of behavior is part of the surface. Consider an Comparable interface:

interface Comparable<T> {
    public int cmp(T that);
    public boolean lt(T that);  // less than
    public boolean le(T that);  // less than or equal
    public boolean eq(T that);  // equal
    public boolean ne(T that);  // not equal
    public boolean ge(T that);  // greater than or equal
    public boolean gt(T that);  // greater than
}

This is very user-friendly (a nice API with many convenient methods), but tedious to implement. We would like the interface to only include cmp, and implement the other methods automatically in terms of that one required method. Mixins, but more importantly Traits [1],[ 2] solve this problem without falling into the traps of multiple inheritance.

This is done by defining a trait composition so that the traits don't actually end up taking part in the MRO – instead the defined methods are composed into the implementing class.

The Comparable interface could be expressed in Scala as

trait Comparable[T] {
    def cmp(that: T): Int
    def lt(that: T): Boolean = this.cmp(that) <  0
    def le(that: T): Boolean = this.cmp(that) <= 0
    ...
}

When a class then uses that trait, the other methods get added to the class definition:

// "extends" isn't different from Java's "implements" in this case
case class Inty(val x: Int) extends Comparable[Inty] {
    override def cmp(that: Inty) = this.x - that.x
    // lt etc. get added automatically
}

So Inty(4) cmp Inty(6) would be -2 and Inty(4) lt Inty(6) would be true.

Many languages have some support for traits, and any language that has a “Metaobject Protocol (MOP)” can have traits added to it. The recent Java 8 update added default methods which are similar to traits (methods in interfaces can have fallback implementations so that it's optional for implementing classes to implement these methods).

Unfortunately, traits are a fairly recent invention (2002), and are thus fairly rare in the larger mainstream languages.


问:
How do Traits in Scala avoid the "diamond error"?
(Note: I used 'error' instead of 'problem' in the title for obvious reasons.. ;) ).

I did some basic reading on Traits in Scala. They're similar to Interfaces in Java or C#, but they do allow for default implementation of a method.

I was wondering: can't this cause a case of the "diamond problem", which is why many languages avoid multiple inheritance in the first place?

If so, how does Scala handle this?

答:
The diamond problem is the inability to decide which implementation of the method to choose. Scala solves this by defining which implementation to choose as part of the language specifications(read the part about Scala in this Wikipedia article).

Ofcourse, same order definition could also be used in class multiple inheritance, so why bother with traits?

The reason IMO is constructors. Constructors have several limitations that regular methods don't have - they can only be called once per object, they have to be called for each new object, and a child class' constructor must call it's parent's constructor as it's first instruction(most languages will do it implicitly for you if you don't need to pass parameters).

If B and C inherit A, and D inherits B and C, and both B and C's constructors call A's constructor, then D's constructor will call A's constructor twice. Defining which implementations to choose like Scala did with methods won't work here because both B's and C's constructors must be called.

Traits avoid this problem since they don't have constructors.

ContentLicense: CC BY-SA 4.0


答: I'd use a perfect hash function to map your set of n inputs to a unique integer < n, then use that as an index into either an array of outputs (eg a list of n colours) or map it to a unique string in your character set (e.g. convert the number to base 26 and render each base-26 digit as that letter of the alphabet).</p>

Title: Randomized Hash function with no collisions

Body:
Related to the question Which hashing algorithm is best for uniqueness and speed?

Is there a way to create a hash function, or find one, whose hash length depends completely on the input length, has an adjustable hash character set (Since it must be 1-to-1 function the input must comply to this character set constraint as well).

Moreover the most important part is that the hash function generates as random as possible strings. So for example it would be possible to get the following two different results.

```<code>Hash(aaaa)->blue // for character set a-z
</code>```

and

```<code>Hash(aaaz)->pink  // for character set a-z
</code>```

More examples:

```<code>Hash(aa@12a)->dakj@4   // for character set a-z, @, 0-9
</code>```

and

```<code>Hash(a2#46Ww)->@3#0Pdw // for character set a-z A-Z, !-), 0-9
</code>```

Notice
the character length between input and output and the character sets.

What I thought so far was a probability distribution function, there are random distribution functions but I am not sure how to get there.

http://en.wikipedia.org/wiki/Probability_distribution

http://en.wikipedia.org/wiki/Normal_distribution


答:
What I don't understand is this:

Abstractions can be superclasses or interfaces.

If so, why are interfaces specifically praised for their ability to allow loose coupling? I don't see how it's different than using a superclass.

First, subtyping and abstraction are two different things. Subtyping merely means that I can substitute values of one type for values of another type - neither type needs to be abstract.

More importantly, subclasses have a direct dependence on the implementation details of their superclass. That's the strongest kind of coupling there is. In fact, if the base class isn't designed with inheritance in mind, changes to the base class that don't change its behaviour can still break subclasses, and there's no way to know a priori if breakage will occur. This is known as the fragile base class problem.

Implementing an interface doesn't couple you to anything except the interface itself, which contains no behavior.


问:
How to make consistent progress towards the goal of becoming better, as opposed to just coding for fun?
I'm in senior year in high school. I enjoy programming (Java) very much and aspire to do it as a career in the future. However this isn't the topic of this question.

My question is: how can I start making consistent progress towards the goal of becoming a great programmer?

What I mean is this:

I work on my own projects, enjoy doing so and feel like I'm slightly improving with every project I finish.

However, I don't feel like I'm consistently moving towards 'the goal of becoming a great programmer'. I want to have a sense of 'working towards the goal'.

What I feel right now is more like "I'm coding stuff which is a lot of fun and I'm improving, but I don't feel like I'm 'making progress towards my goal'".

"Slightly improving over time because I'm coding stuff" doesn't really feel like "making progress towards a goal".

To those of you who are experienced developers: what advice can you give me on making consistent progress towards the goal of becoming great at programming, as opposed to just coding stuff for fun?

答:
Don't knock coding for fun. The key thing needed to become a great programmer is to actually program. Once you get into college, and eventually business you'll find that very little of school and work involves actual programming. Having the passion for it alone goes a long way.

The other big part of it is reflection. After you wrote code for fun (or in the middle of it if it's lengthy), take a moment to evaluate what you've done. What went well? What sucked? Why were things good/sucky? How can you do more of the good things and less of the sucky things?

And then go code something else fun and interesting.


问:
How did programmers implement Linked list ideas before the object oriented paradigm?
Linked lists, as far as I have seen, are largely implemented using object-oriented ideas. (having an object that holds some information and the address of the next link). How were Linked-lists implemented before the object-oriented paradigm came out? Were they only invented(?) once the OOP was developed?</p>

答: They used, for example in C, struct for simulating a node; and pointers to link the nodes</p>


问:
Why do websites restrict the number & choice of characters in a password?
Registering on an insurance company's website right now, and my password is 16 characters long, using a nice variety of letters, numbers, special characters, etc. However, here's their list of restrictions:

Note your password:

must be between 6 and 12 characters

must not contain spaces, special/international characters

must not contain your user name, first name or last name

is case-sensitive

should contain at least 1 number and 1 letter

I can understand minimum 6 characters, not allowing parts of your name, being case-sensitive, and needing at least 1 number and letter. The part I don't get is restricting your choice of characters you can use, and having an upper bound.

Why do websites do this? The only thing I can think of it they don't know the basics of hashing a password, which would secure it better than anything, and get rid of any security concerns.

If I choose to type DELETE FROM users WHERE 1=1 as my password, I should be allowed to. PHP's MD5 hash of it becomes fe5d54132b51b7d65ab89b739b600b4b which I don't think will harm anything.

答:
This decision seems to be based around what is practical for most users. Unlike programmers and techies, many users of online banking seem to have difficulty remembering a 4 character pin, let alone a password of decent length. Which is one of the drivers for 2-factor authentication - give them a device which produces a password so all they need to do is not lose the device!

With respect to the "why no special characters" - it isn't laziness, it's a sensible decision on reducing the potential attack landscape. If you allow apostrophes, hashes, equals signs etc, you need to be 100% confident your input validation routine will catch SQL injection attempts for example - if you whitelist only those chars you want to appear in the input, you save yourself a whole lot of potential damage.

I agree in principle with Matteo - in an ideal world passwords should only be stored with a 1 way hash, however a bank would lose customers if they did this, so there has to be a way. Often, in addition to the hashes stored in the main database, there is an encrypted field, either in the same database, or in a separate passwords database just for this function


答:
Incrementally expand your breadth and depth of experience, e.g.:

Read parts of the Java Language Spec, the VM Spec, and Effective Java. Programmers should know about things like "precise exceptions," the fact that reading or writing a pointer is atomic, and how to use wildcard generic types.

Write programs in various domains like mobile apps, web sites, robotics, and development tools.

Learn more programming languages, say, JavaScript, Smalltalk, and Clojure.

Deliver software to users. Do additional releases, making it better for them.

Write a program with other programmers. Use source code control (e.g. git or svn).

Title: How to make consistent progress towards the goal of becoming better, as opposed to just coding for fun?

Body:
I'm in senior year in high school. I enjoy programming (Java) very much and aspire to do it as a career in the future. However this isn't the topic of this question.

My question is: how can I start making consistent progress towards the goal of becoming a great programmer?

What I mean is this:

I work on my own projects, enjoy doing so and feel like I'm slightly improving with every project I finish.

However, I don't feel like I'm consistently moving towards 'the goal of becoming a great programmer'. I want to have a sense of 'working towards the goal'.

What I feel right now is more like "I'm coding stuff which is a lot of fun and I'm improving, but I don't feel like I'm 'making progress towards my goal'".

"Slightly improving over time because I'm coding stuff" doesn't really feel like "making progress towards a goal".

To those of you who are experienced developers: what advice can you give me on making consistent progress towards the goal of becoming great at programming, as opposed to just coding stuff for fun?


答: Linked list have nothing to do with OOP, in fact they predate OOP by quite a bit. Linked list are implemented simply by having a recursive structure, this is in my opinion conceptually easiest to understand in assembly -- you allocate some memory, and the first bytes of that memory serve as a pointer to the next/previous.  In assembly you don't have to worry about the "type" and just think of it as another pointer, so the fact that it is recursive is not something you need to think about -- you don't have to think about how something can refer to itself in its definition.</p>

Title: How did programmers implement Linked list ideas before the object oriented paradigm?

Body: Linked lists, as far as I have seen, are largely implemented using object-oriented ideas. (having an object that holds some information and the address of the next link). How were Linked-lists implemented before the object-oriented paradigm came out? Were they only invented(?) once the OOP was developed?</p>


问:
Are there any algorithms for splitting or combining words into their more common form?
Are there any existing algorithms which can look through a list of words and split or combine words into their more common form?

For example, I have a list of many business names in the health care industry. The word "healthcare" is often written "health care". There are also business names which might be split or combined, such as "Walmart" and "Wal mart".

Are there any algorithms which can look at my list of words and identify that "healthcare" is more often written as two words, and that "Wal mart" is more often written as a single word?

I'm looking for the names of existing algorithms (which can help when searching the web), or links to existing white-papers or blog posts.

I'd prefer an algorithm that doesn't depend on a dictionary or other external list of words or business names.

EDITS:

Background:

I already have some code that is moderately successful at this task. The code was thrown together without much rigor. I hoped there were some established algorithms, which would likely be more academic and complete then what I've come up with. This question is not about the method I've come up with, but saying "it's impossible" doesn't convince me.

Clarification:

The "more common form" of a word is the way the word(s) are most often written. For example, "Walmart" appeared many times, and "Wal mart" appeared many times, but "Walmart" appeared more often then "Wal mart" and so "Walmart" is the "more common form" of the word.

I don't expect this algorithm to produce perfect results. Like any machine learning problem, I expect the results to be dependent on the quality of data I give it, and how much data I have.

答:
One way to solve it is to use the Levenshtein Edit Distance Algorithm.

Basically you take whatever string was entered, and then you compute the LED value of every word or phrase that starts with the same letter in your corpus (dictionary).  The one with the lowest value is the "proper" form of the word or phrase.  It's rare for someone to mistype the first letter of a word, so this approach works pretty well if you've got a decent corpus to work from.  There are other related algorithms that may work slightly better or worse depending on what you're matching, but I've used LED for fuzzy string searches for many years, and I've always been fairly impressed with how well it works.  I didn't quite follow what your input data was like, so it may or may not work if you don't have reliable word boundaries, though you may be able to modify LED a bit to get it to work even without good word boundaries (maybe one pass treating all existing word boundaries as if they're reliable, and then another pass through with a sliding window of two "words" at a time.  If you get a lower LED on the combination than you get for the sum of the two words, then use the combination or something.

Anyway, it's an interesting puzzle.  I suspect whatever you come up with will probably use some variant of LED.


答:
Above all, code. Code lots. And reflect on it. That's how you learn to value other things, because you feel the pain that leads to a motivation for a solution. While doing that:

Work with other people on projects

Learn from people better than you and be humble

Learn to value the parts that are not strictly coding but rather help with quality

Get perspective from other programming paradigms and languages

In other words, some of the best ways to become a better programmer are not new coding techniques per se. Similarly, they're not things you learn in college either. So let's break it down a bit more.

Regarding #1. As an observation, you will likely be working on a team in the future, but for many things you likely are not working on a team now given that you are in high school. Working on a team means a few things: tolerating other people's coding styles, other people's designs and architectures, Bob's bad taco breath on Taco Tuesday's, submitting code to a repository, having a build server, and having other people hate on your beloved code. Things you can do now:

Learn about a source control system. Use one for your personal projects. I recommend Mercurial or Git. Learn about and use branching; branching is not just some shiny concept it's a real tool in making sure code produced by a team is stable when it reaches production.

Set up a continuous build server of some sort. This won't take that long. Use this build server with your source control for one or more of your projects.

Buy gum for Bob.

Regarding #2. Find people better than you to learn from. This may be hard in high school. Look for people that are humble, don't routinely spout specifications, avoid flame wars, and are respected by others. Then read their code and watch how they interact with people around them.

Regarding #3. Learn what unit tests are if you don't know and why people write them (hint, it's not only for correctness of code). Learn a testing framework like NUnit etc. Find out how mocking can fit into (but is not equivalent to) unit testing. Understand what it means to write testable code - this tends to also be more modular and have better architecture too. Even though they are not always appropriate, understand dependency injectors/dependency injection. I write C++ daily without a dependency injector but the concepts are still applied from time to time in my code and it makes it better.

Regarding #4. Learn categorically new ways to program things and approach problems. This will probably make sense do do once you know Java well. It's like learning about programming patterns: learn it after you've done a bunch of programming (>10K lines of code) so you can really feel their worth and recognize patterns you've already done. Similarly, other languages' paradigms can help you in your current language sometimes because you may simulate a portion of a concept to best solve a problem. It also doesn't hurt to study a bit of history here.

Also, as a bonus: learn how to communicate your ideas well. I had much frustration for many years because I was poor at communicating my ideas and they were stuck in my head. This takes practice and perseverance, but frees you from being alone with your ideas.

Most of these things you will not learn in college. You will learn about algorithms, theory, perhaps the software engineering practices flavor of the month. But these things (with the exception of which source control is the current flavor, the concepts remaining similar) will hopefully change less and help you more. That's not to down on the theory, just to supplement it. I've written a couple state machines in the last week or two.


问:
What security practices should you be aware of when writing software?
What different types of security do there exist? Why and when should they be implemented?

Example: SQL Injection Prevention

答:
Web applications:

Based on the number of attacks - see stats by Verizon, OWASP, WHID and others - the single biggest thing you can do to improve the security of a web application is implement solid input validation. Do not trust anything the client/browser sends you. This will pretty much sort your SQL injection issue, and help out in a number of other areas including field/buffer overflow.


问:
Dependency injection for request variables in a web application
I'm working a PHP 5.5/MySQL web application.

If a class depends partly on some global GET and POST variables for its members, should I just refer to them directly from within the class, or should I have them as arguments in the constructor or some other initiating function?

```<code>class myclass {
  protected $id;
  public function __construct() {
    $this->id = (int)$_GET['id'];
  }
}
$myclass = new myclass();
</code>```

Or

```<code>class myclass {
  protected $id;
  public function __construct($id) {
    $this->id = (int)$id;
  }
}
$myclass = new myclass($_GET['id']);
</code>```

How do MVC frameworks handle this issue?

答:
The whole point of DI is to make your functions independent from the Environment, namely the Global variables. That means:

```<code>function bad () {
    $id = $_GET['id'];
    ...
</code>```

Is as Bad as:

```<code>function bad () {
    global $db;
    ...
</code>```

In both examples you need to pass the function/method dependencies via function arguments. To understand it better imagine if at some point you needed to create an instance of the class, but when you don't have the id in the query string. Another example is if you later decided to implement the same functionality via POST as well. So you need to go and replace all of those $_GET variables with $_REQUEST.

So if I were you I'd definitely go for the second approach. Also it is not related to MVC design-pattern at all. Different frameworks might suggest different practices or don't suggest anything at all.

Body:
The whole point of DI is to make your functions independent from the Environment, namely the Global variables. That means:

function bad () {
    $id = $_GET['id'];
    ...

Is as Bad as:

function bad () {
    global $db;
    ...

In both examples you need to pass the function/method dependencies via function arguments. To understand it better imagine if at some point you needed to create an instance of the class, but when you don't have the id in the query string. Another example is if you later decided to implement the same functionality via POST as well. So you need to go and replace all of those $_GET variables with $_REQUEST.

So if I were you I'd definitely go for the second approach. Also it is not related to MVC design-pattern at all. Different frameworks might suggest different practices or don't suggest anything at all.


问:
Is it a good practice to decouple the membership system?
Currently I'm developing a project that basically is built with ASP.NET Web API. The membership system I'm using is ASP.NET Identity. The only problem I'm seeing with this is that the membership system is being highly coupled with the API I'm bulding.

In that case I've thought on bulding interfaces to expose the membership system functionalities the app needs and then use dependency injection to inject the current Identity system.

The only thing is that on all the time I've been looking on the internet about authentication and authorization in ASP.NET I've never seem this done. So I've started to wonder whether this is or not a good practice.

Is this a good practice or no? If not, why?

答:
Asp.net membership provider is decoupled in itself. In fact it is an implementation of MembershipProvider base class. SqlMembershipProvider is a concrete implementation of the former.

Is decoupling membership a good practice? -> Yes.

Decoupling is generally good for making the functionality reusable for diverse clients. Tomorrow if some android clients want to make use of the authentication module it can, provided it is exposed over http via wcf or web api. Writing software for wcf/webapi forces us to make our logic a decoupled and independent on it own to some debatable degree.

But a more important question is, is it practical? Can you implement this in the software you are trying to create? That is a call one should take after accessing how quickly you want to deliver the software. So once you start thinking on these lines, though the prospect of your code being used up by clients in other technology might seem cool, its actually bad for the budget or delivery concerns. Hence you might not go for decoupling to such degree.

But if you are using the framework provided feature, the mechanism is already decoupled for you. It obviously states this is a good practice. In other words, one can argue its already there because it is a good practice.


问:
Determine how two images should be combined to produce the original image
Suppose I have two similar images as follows

Image 1 (base)

Image 2 (target)

The second image is basically a variation of the first image, except with a green oval slapped on top (indeed, I used image1 as the base to produce image2). To save space, I realize that instead of storing two separate images, I simply need to store the difference and then record the offset in, say, a text file.

So I would go and arbitrarily crop out that oval that I want, and I've effectively shaved off 2 KB in total because my images are solid colors so it's nicely compressed.

This is (or was?) a common technique used in various applications such as games to push down filesize, especially if you have a single image with dozens of variations, but those variations cover maybe 10% of the entire image, so there's a lot of redundant data. And if you're working with full 32bpp with lots and lots of color everywhere, that can add up quite quickly.

Problem

The problem I'm interested in is this: given the base image (image 1) and the cropped variation, merge them together in such a way that you end up with the original image (image 2)

Ideas

If the cropped variation preserved its position by simply removing all the redundant pixels, then the problem is already solved. However, that isn't always the case.

My approach is largely based on the fact that the target image is derived from the base image. For the above examples, the difference is a single green oval. Because I sloppily cropped out the oval without making any effort to isolate it from the background, I happen to have given myself a way to determine whether the cropped image "fits" in place.

So for example, if I were to randomly place the cropped image somewhere in the middle, I might get something like this

Now when you compare it to the base image, you can see that the red and blue rectangles are slightly off by a lot, and it is obviously visually incorrect.

If I didn't know anything about the surrounding pixels (for example, if the cropped variation was simply the green oval), then it would be impossible to reproduce the target image without going in there manually.

I can indirectly quantify how "close" my candidate image is to the target image by taking the sum of the differences between all pixels between the candidate image and the base image: the only pixels that should be different are the ones that make up the variation; the rest of the surrounding pixels that just happened to be in the rectangle should be exactly the same as the base image and should contribute a difference of 0.

Basic Solution

A brute-force approach would basically compute the sum of all pixel differences of every possible position that the cropped image can be placed, and then return all the positions that minimize this sum. For sufficiently complex images, the chances that there will be multiple results is pretty small compared to simple images.

At some point I realized that I only have to consider the pixels inside the cropped image's rectangle, because those are the only pixels in the candidate image that changes compared to the base image, so this avoids some unnecessary computation.

Improvements?

My idea seems kind of slow. Well, it'll likely take less than a minute for images of size 1280x960 or 1920x1080p, and it's still a lot faster than doing it by hand.

Can my approach be improved? For example, do I really need to try every possible combination?

It would be interesting to see if there were other ways to approach the problem as well.

答:
You're basically reinventing video compression.  See e.g this introductory document describing how MPEG-2 does it, or this for MPEG-4/H264.  To address a couple of points in your post:

The search can be done much more efficiently than a brute-force scan over all possibilities by starting on a coarse grid (or at lower resolution) to get an estimate of the motion, and then refining it.

I believe one of the things MPEG-4 adds to MPEG-2's approach is some notion of segmented regions of a scene (or sprite coding), which allows better compression of objects moving against a static background, layered cel animations and the like.  The term "object based video" is often used.


答:
Another important point is unit testing. If you inject the dependencies of a class, you can easily instantiate them in unit tests.

You might want to look at Misko Hevery's
clean code talk about global state (He has few other good talks about OOD)

Title: Dependency injection for request variables in a web application

Body:
I'm working a PHP 5.5/MySQL web application.

If a class depends partly on some global GET and POST variables for its members, should I just refer to them directly from within the class, or should I have them as arguments in the constructor or some other initiating function?

```<code>class myclass {
  protected $id;
  public function __construct() {
    $this->id = (int)$_GET['id'];
  }
}
$myclass = new myclass();
</code>```

Or

```<code>class myclass {
  protected $id;
  public function __construct($id) {
    $this->id = (int)$id;
  }
}
$myclass = new myclass($_GET['id']);
</code>```

How do MVC frameworks handle this issue?


答:
Well you can always translate OOP code back into non-OOP code (or rather, non OOP-looking code). Actually you can code in an OOP way in any language, but it will not be as convenient as OOP languages.

```<code>class Node {
    int data;
    Node *next, *prev;
    public:
    void remove() { // example method
        next->prev = prev;
        prev->next = next;
    }
};
</code>```

becomes, in the first step:

```<code>struct Node {
    int data;
    Node *next, *prev;
};

void remove(Node* self) {
    self->next->prev = prev;
    self->prev->next = next;
}
</code>```

or, if you don't have structs:

```<code>void remove(int *data, int **nextdata, int **prevdata) { // etc.
</code>```

I don't know if it did look like this, but it very well could.

Body:
Well you can always translate OOP code back into non-OOP code (or rather, non OOP-looking code). Actually you can code in an OOP way in any language, but it will not be as convenient as OOP languages.

class Node {
    int data;
    Node *next, *prev;
    public:
    void remove() { // example method
        next->prev = prev;
        prev->next = next;
    }
};

becomes, in the first step:

struct Node {
    int data;
    Node *next, *prev;
};

void remove(Node* self) {
    self->next->prev = prev;
    self->prev->next = next;
}

or, if you don't have structs:

void remove(int *data, int **nextdata, int **prevdata) { // etc.

I don't know if it did look like this, but it very well could.