问:
How to make this design closer to proper DDD?
I've read about DDD for days now and need help with this sample design. All the rules of DDD make me very confused to how I'm supposed to build anything at all when domain objects are not allowed to show methods to the application layer; where else to orchestrate behaviour? Repositories are not allowed to be injected into entities and entities themselves must thus work on state. Then an entity needs to know something else from the domain, but other entity objects are not allowed to be injected either? Some of these things makes sense to me but some don't. I've yet to find good examples of how to build a whole feature as every example is about Orders and Products, repeating the other examples over and over. I learn best by reading examples and have tried to build a feature using the information I've gained about DDD this far.

I need your help to point out what I do wrong and how to fix it, most preferably with code as "I would not recomment doing X and Y" is very hard to understand in a context where everything is just vaguely defined already. If I can't inject an entity into another it would be easier to see how to do it properly.

In my example there are users and moderators. A moderator can ban users, but with a business rule: only 3 per day. I did an attempt at setting up a class diagram to show the relationships (code below):

```<code>interface iUser
{
    public function getUserId();
    public function getUsername();
}

class User implements iUser
{
    protected $_id;
    protected $_username;

    public function __construct(UserId $user_id, Username $username)
    {
        $this->_id          = $user_id;
        $this->_username    = $username;
    }

    public function getUserId()
    {
        return $this->_id;
    }

    public function getUsername()
    {
        return $this->_username;
    }
}

class Moderator extends User
{
    protected $_ban_count;
    protected $_last_ban_date;

    public function __construct(UserBanCount $ban_count, SimpleDate $last_ban_date)
    {
        $this->_ban_count       = $ban_count;
        $this->_last_ban_date   = $last_ban_date;
    }

    public function banUser(iUser &$user, iBannedUser &$banned_user)
    {
        if (! $this->_isAllowedToBan()) {
            throw new DomainException('You are not allowed to ban more users today.');
        }

        if (date('d.m.Y') != $this->_last_ban_date->getValue()) {
            $this->_ban_count = 0;
        }

        $this->_ban_count++;

        $date_banned        = date('d.m.Y');
        $expiration_date    = date('d.m.Y', strtotime('+1 week'));

        $banned_user->add($user->getUserId(), new SimpleDate($date_banned), new SimpleDate($expiration_date));
    }

    protected function _isAllowedToBan()
    {
        if ($this->_ban_count >= 3 AND date('d.m.Y') == $this->_last_ban_date->getValue()) {
            return false;
        }

        return true;
    }
}

interface iBannedUser
{
    public function add(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date);
    public function remove();
}

class BannedUser implements iBannedUser
{
    protected $_user_id;
    protected $_date_banned;
    protected $_expiration_date;

    public function __construct(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date)
    {
        $this->_user_id         = $user_id;
        $this->_date_banned     = $date_banned;
        $this->_expiration_date = $expiration_date;
    }

    public function add(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date)
    {
        $this->_user_id         = $user_id;
        $this->_date_banned     = $date_banned;
        $this->_expiration_date = $expiration_date;
    }

    public function remove()
    {
        $this->_user_id         = '';
        $this->_date_banned     = '';
        $this->_expiration_date = '';
    }
}

// Gathers objects
$user_repo = new UserRepository();
$evil_user = $user_repo->findById(123);

$moderator_repo = new ModeratorRepository();
$moderator = $moderator_repo->findById(1337);

$banned_user_factory = new BannedUserFactory();
$banned_user = $banned_user_factory->build();

// Performs ban
$moderator->banUser($evil_user, $banned_user);

// Saves objects to database
$user_repo->store($evil_user);
$moderator_repo->store($moderator);

$banned_user_repo = new BannedUserRepository();
$banned_user_repo->store($banned_user);
</code>```

Should the User entitity have a 'is_banned' field which can be checked with $user->isBanned();? How to remove a ban? I have no idea.

答:
Move all of your logic which alters state to a service layer (ex: ModeratorService) which knows about both Entities and Repositories.</p>

```<code>ModeratorService.BanUser(User, UserBanRepository, etc.)
{
    // handle ban logic in the ModeratorService
    // update User object
    // update repository
}
</code>```

OwnerDisplayName: Seralize

Body:
Move all of your logic which alters state to a service layer (ex: ModeratorService) which knows about both Entities and Repositories.

ModeratorService.BanUser(User, UserBanRepository, etc.)
{
    // handle ban logic in the ModeratorService
    // update User object
    // update repository
}

OwnerDisplayName: Todd Smith


问:
What's your strongest opinion against functional programming?
Functional programming is one of the oldest programming paradigms. However it isn't used much in the industry compared to more popular paradigms. But it have largely been emphasized in academia.

What's your strongest opinion against functional programming?

答:
Even if I had mastered it, I might be disinclined to use a functional language for a commercial product for the simple reason that they are not widely understood and if I expected the business to grow I would be concerned about the ability to find other developers capable of maintaining or extending it over time.

It's not inconceivable, and you would probably get a higher standard of developer because a javaschool grad with no real hacking skills wouldn't know where to start on a project of that type, but the limited pool of capable developers would certainly be a necessary consideration from a business perspective.

ContentLicense: CC BY-SA 2.5


答:
This question is somewhat subjective and leads to more of a discussion than a direct answer, which, as someone else has pointed out - isn't appropriate for the stackoverflow format. That said, I think you just need some coded examples on how to tackle problems, so I'll give it a shot, just to give you some ideas.

The first thing I'd say is:

"domain objects are not allowed to show methods to the application layer"

That is simply not true - I'd be interested to know where you have read this from. The application layer is the orchestrator between UI, Infrastructure & Domain, and therefore obviously needs to invoke methods on domain entities.

I've written a coded example of how I would tackle your problem. I apologise that it's in C#, but I don't know PHP - hopefully you will still get the gist from a structure perspective.

Perhaps I shouldn't have done, but I have slightly modified your domain objects. I couldn't help feel it was slightly flawed, in that the concept of a 'BannedUser' exists in the system, even if the ban has expired.

To start with, here is the application service - this is what the UI would call:

```<code>public class ModeratorApplicationService
{
    private IUserRepository _userRepository;
    private IModeratorRepository _moderatorRepository;

    public void BanUser(Guid moderatorId, Guid userToBeBannedId)
    {
        Moderator moderator = _moderatorRepository.GetById(moderatorId);
        User userToBeBanned = _userRepository.GetById(userToBeBannedId);

        using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())
        {
            userToBeBanned.Ban(moderator);

            _userRepository.Save(userToBeBanned);
            _moderatorRepository.Save(moderator);
        }
    }
}
</code>```

Pretty straight forward. You fetch the moderator doing the ban, the user who the moderator wants to ban, and call the 'Ban' method on the user, passing the moderator. This will modify state of both the moderator & user (explained below), which then needs persisting via their corresponding repositories.

The User class:

```<code>public class User : IUser
{
    private readonly Guid _userId;
    private readonly string _userName;
    private readonly List<ServingBan> _servingBans = new List<ServingBan>();

    public Guid UserId
    {
        get { return _userId; }
    }

    public string Username
    {
        get { return _userName; }
    }

    public void Ban(Moderator bannedByModerator)
    {
        IssuedBan issuedBan = bannedByModerator.IssueBan(this);

        _servingBans.Add(new ServingBan(bannedByModerator.UserId, issuedBan.BanDate, issuedBan.BanExpiry));
    }

    public bool IsBanned()
    {
        return (_servingBans.FindAll(CurrentBans).Count > 0);
    }

    public User(Guid userId, string userName)
    {
        _userId = userId;
        _userName = userName;
    }

    private bool CurrentBans(ServingBan ban)
    {
        return (ban.BanExpiry > DateTime.Now);
    }

}

public class ServingBan
{
    private readonly DateTime _banDate;
    private readonly DateTime _banExpiry;
    private readonly Guid _bannedByModeratorId;

    public DateTime BanDate
    {
        get { return _banDate;}
    }

    public DateTime BanExpiry
    {
        get { return _banExpiry; }
    }

    public ServingBan(Guid bannedByModeratorId, DateTime banDate, DateTime banExpiry)
    {
        _bannedByModeratorId = bannedByModeratorId;
        _banDate = banDate;
        _banExpiry = banExpiry;
    }
}
</code>```

The invariant for a user is that they cannot perform certain actions when banned, so we need to be able to identify if a user is currently banned. To achieve this the user maintains a list of serving bans that have been issued by moderators. The IsBanned() method checks for any serving bans that are yet to expire. When the Ban() method is called, it receives a moderator as a parameter. This then asks the the moderator to issue a ban:

```<code>public class Moderator : User
{
    private readonly List<IssuedBan> _issuedbans = new List<IssuedBan>();

    public bool CanBan()
    {
        return (_issuedbans.FindAll(BansWithTodaysDate).Count < 3);
    }

    public IssuedBan IssueBan(User user)
    {
        if (!CanBan())
            throw new InvalidOperationException("Ban limit for today has been exceeded");

        IssuedBan issuedBan = new IssuedBan(user.UserId, DateTime.Now, DateTime.Now.AddDays(7));

        _issuedbans.Add(issuedBan);

        return issuedBan;
    }

    private bool BansWithTodaysDate(IssuedBan ban)
    {
        return (ban.BanDate.Date == DateTime.Today.Date);
    }
}

public class IssuedBan
{
    private readonly Guid _bannedUserId;
    private readonly DateTime _banDate;
    private readonly DateTime _banExpiry;

    public DateTime BanDate { get { return _banDate;}}

    public DateTime BanExpiry { get { return _banExpiry;}}

    public IssuedBan(Guid bannedUserId, DateTime banDate, DateTime banExpiry)
    {
        _bannedUserId = bannedUserId;
        _banDate = banDate;
        _banExpiry = banExpiry;
    }
}
</code>```

The invariant for the moderator is that it can only issue 3 bans per day. Thus, when the IssueBan method is called, it checks that the moderator doesn't have 3 issued bans with today's date in its list of issued bans. It then adds the newly issued ban to it's list and returns it.

Subjective, and I'm sure someone will disagree with the approach, but hopefully it gives you an idea or how it can fit together.

ContentLicense: CC BY-SA 3.0

Title: How to make this design closer to proper DDD?

Body:
I've read about DDD for days now and need help with this sample design. All the rules of DDD make me very confused to how I'm supposed to build anything at all when domain objects are not allowed to show methods to the application layer; where else to orchestrate behaviour? Repositories are not allowed to be injected into entities and entities themselves must thus work on state. Then an entity needs to know something else from the domain, but other entity objects are not allowed to be injected either? Some of these things makes sense to me but some don't. I've yet to find good examples of how to build a whole feature as every example is about Orders and Products, repeating the other examples over and over. I learn best by reading examples and have tried to build a feature using the information I've gained about DDD this far.

I need your help to point out what I do wrong and how to fix it, most preferably with code as "I would not recomment doing X and Y" is very hard to understand in a context where everything is just vaguely defined already. If I can't inject an entity into another it would be easier to see how to do it properly.

In my example there are users and moderators. A moderator can ban users, but with a business rule: only 3 per day. I did an attempt at setting up a class diagram to show the relationships (code below):

```<code>interface iUser
{
    public function getUserId();
    public function getUsername();
}

class User implements iUser
{
    protected $_id;
    protected $_username;

    public function __construct(UserId $user_id, Username $username)
    {
        $this->_id          = $user_id;
        $this->_username    = $username;
    }

    public function getUserId()
    {
        return $this->_id;
    }

    public function getUsername()
    {
        return $this->_username;
    }
}

class Moderator extends User
{
    protected $_ban_count;
    protected $_last_ban_date;

    public function __construct(UserBanCount $ban_count, SimpleDate $last_ban_date)
    {
        $this->_ban_count       = $ban_count;
        $this->_last_ban_date   = $last_ban_date;
    }

    public function banUser(iUser &$user, iBannedUser &$banned_user)
    {
        if (! $this->_isAllowedToBan()) {
            throw new DomainException('You are not allowed to ban more users today.');
        }

        if (date('d.m.Y') != $this->_last_ban_date->getValue()) {
            $this->_ban_count = 0;
        }

        $this->_ban_count++;

        $date_banned        = date('d.m.Y');
        $expiration_date    = date('d.m.Y', strtotime('+1 week'));

        $banned_user->add($user->getUserId(), new SimpleDate($date_banned), new SimpleDate($expiration_date));
    }

    protected function _isAllowedToBan()
    {
        if ($this->_ban_count >= 3 AND date('d.m.Y') == $this->_last_ban_date->getValue()) {
            return false;
        }

        return true;
    }
}

interface iBannedUser
{
    public function add(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date);
    public function remove();
}

class BannedUser implements iBannedUser
{
    protected $_user_id;
    protected $_date_banned;
    protected $_expiration_date;

    public function __construct(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date)
    {
        $this->_user_id         = $user_id;
        $this->_date_banned     = $date_banned;
        $this->_expiration_date = $expiration_date;
    }

    public function add(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date)
    {
        $this->_user_id         = $user_id;
        $this->_date_banned     = $date_banned;
        $this->_expiration_date = $expiration_date;
    }

    public function remove()
    {
        $this->_user_id         = '';
        $this->_date_banned     = '';
        $this->_expiration_date = '';
    }
}

// Gathers objects
$user_repo = new UserRepository();
$evil_user = $user_repo->findById(123);

$moderator_repo = new ModeratorRepository();
$moderator = $moderator_repo->findById(1337);

$banned_user_factory = new BannedUserFactory();
$banned_user = $banned_user_factory->build();

// Performs ban
$moderator->banUser($evil_user, $banned_user);

// Saves objects to database
$user_repo->store($evil_user);
$moderator_repo->store($moderator);

$banned_user_repo = new BannedUserRepository();
$banned_user_repo->store($banned_user);
</code>```

Should the User entitity have a 'is_banned' field which can be checked with $user->isBanned();? How to remove a ban? I have no idea.

Body:
This question is somewhat subjective and leads to more of a discussion than a direct answer, which, as someone else has pointed out - isn't appropriate for the stackoverflow format. That said, I think you just need some coded examples on how to tackle problems, so I'll give it a shot, just to give you some ideas.

The first thing I'd say is:

"domain objects are not allowed to show methods to the application layer"

That is simply not true - I'd be interested to know where you have read this from. The application layer is the orchestrator between UI, Infrastructure & Domain, and therefore obviously needs to invoke methods on domain entities.

I've written a coded example of how I would tackle your problem. I apologise that it's in C#, but I don't know PHP - hopefully you will still get the gist from a structure perspective.

Perhaps I shouldn't have done, but I have slightly modified your domain objects. I couldn't help feel it was slightly flawed, in that the concept of a 'BannedUser' exists in the system, even if the ban has expired.

To start with, here is the application service - this is what the UI would call:

public class ModeratorApplicationService
{
    private IUserRepository _userRepository;
    private IModeratorRepository _moderatorRepository;

    public void BanUser(Guid moderatorId, Guid userToBeBannedId)
    {
        Moderator moderator = _moderatorRepository.GetById(moderatorId);
        User userToBeBanned = _userRepository.GetById(userToBeBannedId);

        using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())
        {
            userToBeBanned.Ban(moderator);

            _userRepository.Save(userToBeBanned);
            _moderatorRepository.Save(moderator);
        }
    }
}

Pretty straight forward. You fetch the moderator doing the ban, the user who the moderator wants to ban, and call the 'Ban' method on the user, passing the moderator. This will modify state of both the moderator & user (explained below), which then needs persisting via their corresponding repositories.

The User class:

public class User : IUser
{
    private readonly Guid _userId;
    private readonly string _userName;
    private readonly List<ServingBan> _servingBans = new List<ServingBan>();

    public Guid UserId
    {
        get { return _userId; }
    }

    public string Username
    {
        get { return _userName; }
    }

    public void Ban(Moderator bannedByModerator)
    {
        IssuedBan issuedBan = bannedByModerator.IssueBan(this);

        _servingBans.Add(new ServingBan(bannedByModerator.UserId, issuedBan.BanDate, issuedBan.BanExpiry));
    }

    public bool IsBanned()
    {
        return (_servingBans.FindAll(CurrentBans).Count > 0);
    }

    public User(Guid userId, string userName)
    {
        _userId = userId;
        _userName = userName;
    }

    private bool CurrentBans(ServingBan ban)
    {
        return (ban.BanExpiry > DateTime.Now);
    }

}

public class ServingBan
{
    private readonly DateTime _banDate;
    private readonly DateTime _banExpiry;
    private readonly Guid _bannedByModeratorId;

    public DateTime BanDate
    {
        get { return _banDate;}
    }

    public DateTime BanExpiry
    {
        get { return _banExpiry; }
    }

    public ServingBan(Guid bannedByModeratorId, DateTime banDate, DateTime banExpiry)
    {
        _bannedByModeratorId = bannedByModeratorId;
        _banDate = banDate;
        _banExpiry = banExpiry;
    }
}

The invariant for a user is that they cannot perform certain actions when banned, so we need to be able to identify if a user is currently banned. To achieve this the user maintains a list of serving bans that have been issued by moderators. The IsBanned() method checks for any serving bans that are yet to expire. When the Ban() method is called, it receives a moderator as a parameter. This then asks the the moderator to issue a ban:

public class Moderator : User
{
    private readonly List<IssuedBan> _issuedbans = new List<IssuedBan>();

    public bool CanBan()
    {
        return (_issuedbans.FindAll(BansWithTodaysDate).Count < 3);
    }

    public IssuedBan IssueBan(User user)
    {
        if (!CanBan())
            throw new InvalidOperationException("Ban limit for today has been exceeded");

        IssuedBan issuedBan = new IssuedBan(user.UserId, DateTime.Now, DateTime.Now.AddDays(7));

        _issuedbans.Add(issuedBan);

        return issuedBan;
    }

    private bool BansWithTodaysDate(IssuedBan ban)
    {
        return (ban.BanDate.Date == DateTime.Today.Date);
    }
}

public class IssuedBan
{
    private readonly Guid _bannedUserId;
    private readonly DateTime _banDate;
    private readonly DateTime _banExpiry;

    public DateTime BanDate { get { return _banDate;}}

    public DateTime BanExpiry { get { return _banExpiry;}}

    public IssuedBan(Guid bannedUserId, DateTime banDate, DateTime banExpiry)
    {
        _bannedUserId = bannedUserId;
        _banDate = banDate;
        _banExpiry = banExpiry;
    }
}

The invariant for the moderator is that it can only issue 3 bans per day. Thus, when the IssueBan method is called, it checks that the moderator doesn't have 3 issued bans with today's date in its list of issued bans. It then adds the newly issued ban to it's list and returns it.

Subjective, and I'm sure someone will disagree with the approach, but hopefully it gives you an idea or how it can fit together.

OwnerDisplayName: David Masters


问:
Design Patterns for Coordinating Change Event Listeners
I've been working with the Observer pattern in JavaScript using various popular libraries for a number of years (YUI & jQuery). It's often that I need to observe a set of property value changes (e.g. respond only when 2 or more specific values change). Is there a elegant way to 'subscribe' the handler so that it is only called one time? Is there something I'm missing or doing wrong in my design?</p>

答:
Yes. For this I returned to the original "Gang of Four" book on Design Patterns, then did some research online.

Mediator - Define an object that encapsulates how a set of objects
  interact. Mediator promotes loose coupling by keeping objects from
  referring to each other explicitly, and it lets you vary their
  interaction independently. It is responsible for coordinating interactions for a group of objects.

State - Allow an object to alter its behavior when its internal state
  changes.

Here is an example of JavaScript mediator. Skip to the bottom for usage. Other examples may or may not be more relevant for you. But it exemplifies the notion.

"Instead of using the Observer pattern to explicitly set many-to-many
  listeners and events, Mediator allows you to broadcast events globally
  across colleagues." — Paul Marcotte

Here is some code:

```<code>//A State Object is simple encapsulation of runtime activity potentially embedded in Mediator.
var interactionState = { //record state, perhaps array, look up function, or even boolean flag.}
</code>```

//A Mediator Adds and Removes components, and Broadcasts Events.

//A Mediator loops through added objects and references state to determine if action should be taken.

```<code>    for (var c in components) {
        if (typeof components[c]["on" + e] == "function")

          //Add in state comparison
          // if ( interactionState...) //is ready to fire action.
            //{ fire action }

          {
            try {
                //debug("Mediator calling " + e + " on " + c);
                var s = source || components[c];
                components[c]["on" + e].apply(s, a);
            } catch (err) {
                debug(["Mediator error.", e, a, s, err].join(' '));
            }
        }
    }
</code>```

Your implementation of the "apply" behavior is probably different, and may be simplified.

```<code>Is there a elegant way to 'subscribe' the handler so that it is only called one time?
</code>```

I wouldn't think of it as 'limiting the events'. There is probably no real performance gain by doing this anyway. The perspective above, is to introduce a decision mechanism that says, "We have had 2 or more objects firing events, lets do this special task".

The Mediator encapsulates the decision mechanism, the state object encapsulates the runtime accumulation of information. Keep in mind that, at some point the state may need to be reset. This cleanup behavior would be sensible to be placed within the Mediator.

It may very well be the case that you can have your Observer listening for published events, then calls the Mediator to review the State, which makes the determination of interaction, if it is relevant, then broadcasts event with instruction to execute their special behavior.

EDIT: Also check out Evented Views. This is an exceptional article on the topic.

Body:
Yes. For this I returned to the original "Gang of Four" book on Design Patterns, then did some research online.

Mediator - Define an object that encapsulates how a set of objects
  interact. Mediator promotes loose coupling by keeping objects from
  referring to each other explicitly, and it lets you vary their
  interaction independently. It is responsible for coordinating interactions for a group of objects.

State - Allow an object to alter its behavior when its internal state
  changes.

Here is an example of JavaScript mediator. Skip to the bottom for usage. Other examples may or may not be more relevant for you. But it exemplifies the notion.

"Instead of using the Observer pattern to explicitly set many-to-many
  listeners and events, Mediator allows you to broadcast events globally
  across colleagues." — Paul Marcotte

Here is some code:

//A State Object is simple encapsulation of runtime activity potentially embedded in Mediator.
var interactionState = { //record state, perhaps array, look up function, or even boolean flag.}

//A Mediator Adds and Removes components, and Broadcasts Events.

//A Mediator loops through added objects and references state to determine if action should be taken.

    for (var c in components) {
        if (typeof components[c]["on" + e] == "function")

          //Add in state comparison
          // if ( interactionState...) //is ready to fire action.
            //{ fire action }

          {
            try {
                //debug("Mediator calling " + e + " on " + c);
                var s = source || components[c];
                components[c]["on" + e].apply(s, a);
            } catch (err) {
                debug(["Mediator error.", e, a, s, err].join(' '));
            }
        }
    }

Your implementation of the "apply" behavior is probably different, and may be simplified.

Is there a elegant way to 'subscribe' the handler so that it is only called one time?

I wouldn't think of it as 'limiting the events'. There is probably no real performance gain by doing this anyway. The perspective above, is to introduce a decision mechanism that says, "We have had 2 or more objects firing events, lets do this special task".

The Mediator encapsulates the decision mechanism, the state object encapsulates the runtime accumulation of information. Keep in mind that, at some point the state may need to be reset. This cleanup behavior would be sensible to be placed within the Mediator.

It may very well be the case that you can have your Observer listening for published events, then calls the Mediator to review the State, which makes the determination of interaction, if it is relevant, then broadcasts event with instruction to execute their special behavior.

EDIT: Also check out Evented Views. This is an exceptional article on the topic.


问:
Prevent Click Fraud in Advertisement system with PHP and Javascript
I would like to build an Advertising project with PHP, MySQL, and Javascript.  I am talking about something like...

Google Adsense

BuySellAds.com

Any other advertising platform

My question is mainly, what do I need to look out for to prevent people cheating the system and any other issues I may encounter?

My design concept.  An Advertisement is a record in the Database, when a page is loaded, using Javascript, it calls my server which in turn will use a PHP script to query the Database and get a random Advertisement.  (It may do kore like get an ad based on demographics or other criteria as well)  The PHP script will then return the Advertisement to the server/website that is calling it and show it on the page as an Image that will have a special tracking link.

I will need to...

Count all impressions (when the Advertisement is shown on the page)

Count all clicks on the Advertisement link

Count all Unique clicks on the Advertisement link

My question is purely on the query and displaying of the Advertisement and nothing to do with the administration side.  If there is ever money involved with my Advertisement buying/selling of adspace, then the stats need to be accurate and make sure people can't easily cheat the system.  Is tracking IP address really the only way to try to prevent click fraud?

I am hoping someone with some experience can clarify I am on the right track?  As well as give me any advice, tips, or anything else I should know about doing something like this?

答:
Nobody has paid for "random advertisements" since 1998.

Serving random advertisements is a useless endeavor. How valuable are feminine product advertisements on sites aimed at men, or vice a versa. I would say they have negative value to me as an advertiser. Doing more sophisticated ad delivery implies a much more sophisticated set of metadata about the viewer, that is for all purposes anonymous unless you are Google in 2012.

PHP and RDMBS for systems like this don't scale.

See what Mochigames did for their in house custom Ad distribution server solution. hint: it isn't PHP or traditional database based.

IP Addresses aren't good for anything other than what they were designed for.

Tracking IP Addresses is the absolutely wrong way to approach this problem. IP Addresses are for routing to its location, nothing more. They are not a globally unique id, and are less than useless as such.

IP addresses aren't unique because of NAT.

IP addresses aren't unique because of spoofing.

IP addresses aren't unique because of anonymous randomizing proxies.

IP addresses are useless in detecting bot nets, the most common click fraud mechanism.

IP addresses are useless in detecting human nets as well.

Deep Pockets

Google and the other big players spend 10s of millions of dollars on this problem every year, maybe more. They can't stop it with all that money and Phd.s in pocket, I doubt some PHP and client side Javascript ( which by definition is useless ) would have any impact at all.

The only way to detect and marginalize click fraud is to apply very sophisticated machine learning algorithms ( this is where the Phd comes into play ) after the fact to look for very broad patterns of behavior ( this is where the money comes into play ) and have that algorithm adapt over time to become more accurate.

Some Click Fraud Acceptance is Inevitable

But even then you have to tune the results in favor of false negative, that is you have to be willing to accept some actual click fraud, because not paying for false positives would completely undermine your trust worthiness to your legit customers.

OwnerDisplayName: CodeDevelopr


问:
Low level Linux graphics
For educational purposes, I'd like to write an application on a Linux environment that can process keyboard events and draw graphics without huge dependencies like X or SDL. I presume that this must be possible, because X and SDL are just programs themselves, so they must rely on other methods inherent to the environment. Is this understanding correct?

If so, where might I learn to write such a program? My limited experience tells me that it would involve making calls to the kernel, and/or writing to special files; however, I haven't been able to find any tutorials on the matter (I am not even sure what to Google).

Also, in case it is relevant, I am running Debian Squeeze on Virtualbox. I have used a netinst cd without networking, so there isn't much installed on it currently. I will install gcc, but I am hoping I can get by with nothing more.

答:
If you want to get input events without using X then you will have to read them out of device nodes.  Linux has a generic input subsystem called evdev that most drivers take advantage of.  So to read input events, you can read from any of the device nodes in /dev/input.

An easy trick to find the mouse device node is to run "cat" on the device nodes one at a time, moving the mouse during each "cat".  If you see data coming out to the screen then that is your mouse device node.  The relevant header file is linux/input.h.  For an example of how to use it, look at the source for xevdev driver.

For low level graphics manipulation, if you are really feeling ambitious, you can generally memory map the framebuffer and do your own bit blts.

Title: Low level Linux graphics


问:
What are some practical uses of the "new" modifier in C# with respect to hiding?
A co-worker and I were looking at the behavior of the new keyword in C# as it applies to the concept of hiding. From the documentation:

Use the new modifier to explicitly hide a member inherited from a base
  class. To hide an inherited member, declare it in the derived class
  using the same name, and modify it with the new modifier.

We've read the documentation, and we understand what it basically does and how it does it. What we couldn't really get a handle on is why you would need to do it in the first place. The modifier has been there since 2003, and we've both been working with .Net for longer than that and it's never come up.

When would this behavior be necessary in a practical sense (e.g.: as applied to a business case)? Is this a feature that has outlived its usefulness or is what it does simply uncommon enough in what we do (specifically we do web forms and MVC applications and some small factor WinForms and WPF)? In trying this keyword out and playing with it we found some behaviors that it allows that seem a little hazardous if misused.

This sounds a little open-ended, but we're looking for a specific use case that can be applied to a business application that finds this particular tool useful.

答:
You may want to have the previous member available thru other name:

```<code>class VehicleClass
{
  public int AnyProperty
  {
    get; set;
  }

  public int AnyFunction() { return 0; }
} // VehicleClass

class IntermediateClass : VehicleClass
{
  public int PreviousAnyProperty
  {
    get { return AnyProperty; }
    set { AnyProperty = value  }
  }

  public int PreviousAnyFunction() { return AnyFunction(); }
} // IntermediateClass

class CarClass : IntermediateClass
{
  public new int AnyProperty
  {
    get ; set ;
  }

  public new int AnyFunction() { return 5; }
} // class CarClass

class ExampleClass
{

  public static void Main()
  {
    using (CarClass MyCar = new CarClass())
    {
      int AnyInt1 = MyCar.PreviousAnyProperty;
      MyCar.PreviousAnyProperty = 7;

      int AnyInt2 = MyCar.PreviousAnyFunction();

      int AnyInt3 = MyCar.AnyProperty;
      MyCar.AnyProperty = 45;

      int AnyInt4 = MyCar.AnyFunction();
    }
  } // static void Main()

} // class CarClass
</code>```

Cheers.

ContentLicense: CC BY-SA 4.0

Body:
You may want to have the previous member available thru other name:

class VehicleClass
{
  public int AnyProperty
  {
    get; set;
  }

  public int AnyFunction() { return 0; }
} // VehicleClass

class IntermediateClass : VehicleClass
{
  public int PreviousAnyProperty
  {
    get { return AnyProperty; }
    set { AnyProperty = value  }
  }

  public int PreviousAnyFunction() { return AnyFunction(); }
} // IntermediateClass

class CarClass : IntermediateClass
{
  public new int AnyProperty
  {
    get ; set ;
  }

  public new int AnyFunction() { return 5; }
} // class CarClass

class ExampleClass
{

  public static void Main()
  {
    using (CarClass MyCar = new CarClass())
    {
      int AnyInt1 = MyCar.PreviousAnyProperty;
      MyCar.PreviousAnyProperty = 7;

      int AnyInt2 = MyCar.PreviousAnyFunction();

      int AnyInt3 = MyCar.AnyProperty;
      MyCar.AnyProperty = 45;

      int AnyInt4 = MyCar.AnyFunction();
    }
  } // static void Main()

} // class CarClass

Cheers.


问:
A programmer should concentrate on at least how many languages?
For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>

答:
Languages are tools to get work done. Some languages are good for some types of problems, others are generally good at all sorts of problem solving. I recommend learning new languages as they come out. Don't get obsessed with what is fashionable this month, but learn what they can do, what they are good at. My advice is 1 new language per year. They come out faster than that, but you are looking to put new tools in your toolbox, not be the fashionable new kid on the block.

One essay that talks about the differences in languages is Paul Graham's "Beating the Averages." I recommend reading it, but one important part is here (he uses "Blub" as a hypothetical language so that you don't go arguing about what your favorite langage can do):

Or how about Perl 4? Between Perl 4 and Perl 5, lexical closures got added to the language. Most Perl hackers would agree that Perl 5 is more powerful than Perl 4. But once you've admitted that, you've admitted that one high level language can be more powerful than another. And it follows inexorably that, except in special cases, you ought to use the most powerful you can get.

This idea is rarely followed to its conclusion, though. After a certain age, programmers rarely switch languages voluntarily. Whatever language people happen to be used to, they tend to consider just good enough.

{snip}

As long as our hypothetical Blub programmer is looking down the power continuum, he knows he's looking down. Languages less powerful than Blub are obviously less powerful, because they're missing some feature he's used to. But when our hypothetical Blub programmer looks in the other direction, up the power continuum, he doesn't realize he's looking up. What he sees are merely weird languages. He probably considers them about equivalent in power to Blub, but with all this other hairy stuff thrown in as well. Blub is good enough for him, because he thinks in Blub.

When we switch to the point of view of a programmer using any of the languages higher up the power continuum, however, we find that he in turn looks down upon Blub. How can you get anything done in Blub? It doesn't even have y.

By induction, the only programmers in a position to see all the differences in power between the various languages are those who understand the most powerful one. (This is probably what Eric Raymond meant about Lisp making you a better programmer.) You can't trust the opinions of the others, because of the Blub paradox: they're satisfied with whatever language they happen to use, because it dictates the way they think about programs.

http://www.paulgraham.com/avg.html

Most of the applications we ship are written in C# or VB. When we needed to add scripting to an application, we chose Python (Lua was the runner-up choice). We're learning F# because that can do some hairy new things that are hard to explain and understand if all one knows is C#/Java/VB.


问:
For an ORM supporting data validation, should constraints be enforced in the database as well?
I have always applied constraints at the database level in addition to my (ActiveRecord) models. But I've been wondering if this is really required?

A little background

I recently had to unit test a basic automated timestamp generation method for a model. Normally, the test would create an instance of the model and save it without validation. But there are other required fields that aren't nullable at the in the table definition, meaning I cant save the instance even if I skip the ActiveRecord validation. So I'm thinking if I should remove such constraints from the db itself, and let the ORM handle them?

Possible advantages if I skip constraints in db, imo -

Can modify a validation rule in the model, without having to migrate
the database.

Can skip validation in testing.

Possible disadvantage?

If its possible that ORM validation fails or is bypassed, howsoever, the database does not check for constraints.

What do you think?

EDIT In this case, I'm using the Yii Framework, which generates the model from the database, hence database rules are generated also (though I could always write them post-generation myself too).

答:
I think you do both to some extent.

The primary constraints should live in the ORM -- programming languages are lots more flexible, it is easier to test and easier to tweak when requirements change; no need to worry about DDL fixes at least. And you generally avoid hard to test data regression issues.

Some very hard and fast constraints should also live in the database. I'm not talking about non-nullable names, for instance. I'm talking about things like referential integrity or requiring some absolutely crucial identifiers. Structural requirements so your code does not need to deal with "what if the Order has a non-existent product".


问:
Should I pay my developers for bugs fixes for a project or work that's still in progress?
We are working with a group of developers on a project. The project is still in progress (not completed) and these developers charge us for time spent on fixing bugs on codes that were not written valid in the first place. I understand that we should pay for changes/new requests if any, but not bugs fixes for a work in progress. We also understand that once the assignment is being deployed to the live site, we may be liable for bugs fixes that may arise after a support period is being exhausted.

The question now is, is it appropriate for such charges to be levied upon us while the project is still in progress?

答:
As others have answered: you should pay whatever it is your contract says you agreed to pay.

It sounds like you may now have issues with your contract and feel you are being taken for a ride. If you are unhappy with your dev team then it is your responsibility to communicate this to them in a clear and amicable way so the issue can be resolved and work can continue. It doesn't sound like you have a particular problem with the team or the work being provided but rather the billing. Have a friendly call or face-to-face meeting and ask them about it. My experience has been that this will resolve most issues quite nicely.

If that doesn't work out for you then there a bunch of great answers to this question already.


问:
If I use Ruby Migrations, do I have to use the rest of Ruby on Rails?
I'm currently trying to come up with a database migrations strategy for my organization.  This includes getting the database scripts into source control, managing versioning, managing releases to QA / Production, managing branching and merging across different release branches, etc.

Ruby Migrations seems to offer solutions to a lot of those problems.  But, from looking at the Ruby on Rails docs, it is unclear to me whether Ruby Migrations can be separated from the rest of the framework.  I work in a primarily .NET shop, but with a lot of other technologies, and with multiple DBMS platforms (SQL Server, Oracle of various versions).  Ruby is not present in our portfolio at all right now, and we have no plans to use it.  If I was to use Ruby Migrations, it would be the only piece of the Ruby on Rails framework that we would want to use.

Can Ruby Migrations be effectively used to manage database changes independently of the rest of the Ruby on Rails framework?  Are there any docs or articles out there that describe this workflow?

(Yes, I know there are other options such as Liquibase but I'm specifically trying to learn about Ruby Migrations with this question.)

答:
I like Sequel a lot.

Sequel supports also migrations

I like Sequel, because it used like SQL, you don't need to use it as ORM, you can use it very easy as an interface to a DB. Sometimes I use Sequel only to generate SQL-commands.

Especially with legacy-DB I prefer Sequel.


问:
Legality of collaborative reverse-engineering
I have been disassembling a large software project on my own, as a hobby. It is an educational exercise and I have learned a lot in the process. That said, I feel that my progress would be considerably quicker if I was to collaborate on the project with other like-minded individuals.

Herein lies the problem -- maybe. I am reversing this software for personal interest and potentially (but unlikely; given the magnitude of the codebase in question) implementing an interoperable service to interact with this software, replacing the vendor's own service. My (very limited) understanding is that this particular use-case is protected under copyright law.

However, my wish is to collaborate with others freely on the Internet, in a similar system employed by open source projects: version control repositories of assembly files, wikis to coordinate and share knowledge, public mailing lists, et cetera. I have a feeling this may be iffy at best.

Is what I want to do blatantly illegal, a gray area or even legally defensible? Would the situation be any different if the collaboration was in private rather than public? If it has any bearing on the answer, I am located in Australia and the software vendor in located in the USA.

答:
My limited understanding is that, in the US, reverse engineering for purposes of interoperability is perfectly legal.  However, I'm not a lawyer and I doubt you are.

What you need to do is find a lawyer who specializes in this sort of thing and who works in your jurisdiction.  In the US, it should be fairly easy to find one by going to your local Bar Association, and the first consultation is unlikely to be expensive.

Never accept legal advice from anybody who happens to post, usually from a potentially different place with potentially different laws, on the net.


答:
The Reactive Extensions framework was designed to address this issue for .NET event handlers. You may be interested in seeing how RX can let you respond to sequences of events, as described in the "Sequencing Events" section of this blog post. Basically, if you are interested in responding only when the user types "ABC" (in that order), you can say:

```<code>IObservable<Key> keyPress =
   Observable.FromEvent<KeyEventArgs>(Application.Current.RootVisual, "KeyUp")
      .Select(ev => ev.EventArgs.Key);

Func<Key, IObservable<Key>> pressedIs =
   key => keyPress.Where(pressedKey => pressedKey == key);

Func<Key, IObservable<Key>> pressedIsNot =
   key => keyPress.Where(pressedKey => pressedKey != key);

IObservable<Unit> abcPressed =
   from firstKeyPressEvent in pressedIs(Key.A)
   from secondKeyPressEvent in pressedIs(Key.B).Take(1).Until(pressedIsNot(Key.B))
   from thirdKeyPressEvent in pressedIs(Key.C).Take(1).Until(pressedIsNot(Key.C))
   select new Unit();

abcPressed.Subscribe(()=> Debug.WriteLine("ABC was pressed."));
</code>```

RxJs is the javascript implementation.

Title: Design Patterns for Coordinating Change Event Listeners

Body: I've been working with the Observer pattern in JavaScript using various popular libraries for a number of years (YUI & jQuery). It's often that I need to observe a set of property value changes (e.g. respond only when 2 or more specific values change). Is there a elegant way to 'subscribe' the handler so that it is only called one time? Is there something I'm missing or doing wrong in my design?</p>

Body:
The Reactive Extensions framework was designed to address this issue for .NET event handlers. You may be interested in seeing how RX can let you respond to sequences of events, as described in the "Sequencing Events" section of this blog post. Basically, if you are interested in responding only when the user types "ABC" (in that order), you can say:

IObservable<Key> keyPress =
   Observable.FromEvent<KeyEventArgs>(Application.Current.RootVisual, "KeyUp")
      .Select(ev => ev.EventArgs.Key);

Func<Key, IObservable<Key>> pressedIs =
   key => keyPress.Where(pressedKey => pressedKey == key);

Func<Key, IObservable<Key>> pressedIsNot =
   key => keyPress.Where(pressedKey => pressedKey != key);

IObservable<Unit> abcPressed =
   from firstKeyPressEvent in pressedIs(Key.A)
   from secondKeyPressEvent in pressedIs(Key.B).Take(1).Until(pressedIsNot(Key.B))
   from thirdKeyPressEvent in pressedIs(Key.C).Take(1).Until(pressedIsNot(Key.C))
   select new Unit();

abcPressed.Subscribe(()=> Debug.WriteLine("ABC was pressed."));

RxJs is the javascript implementation.


问:
Reflective practice in programming using keystroke playback
I'm thinking of applying Reflective Practice to improving my programming skills.  To that end, I want to be able to watch myself writing code.

In general, what is a good method for applying Reflective Practice to the craft of programming?

In particular, if it's a good idea, is there an editor that records keystrokes then plays them back at a later time - possibly running the keys together without delays, or replaying at a 2x/4x/8x accelerated rate?

Screencasting with RecordMyDesktop is an option, but has downsides of waiting for encoding and ending up with a big video file instead of a list of keystrokes.

Update: From "watching myself code" I expect to learn what kind of mistakes I make most frequently or where I waste time while coding. Then I can work on improving those aspects.  It could be certain formatting, syntax or runtime errors, or maybe long pauses that indicate I hadn't considered some issue before I started coding, or maybe I re-write entire functions because my initial design was wrong.  I understand that there's a lot more to programming than the act of writing code and this won't capture all of it.   As recommended I should make more design notes and reflect on those too.

Recording keystrokes may be more helpful to improving my technique in time-limited programming contests, and less helpful for improving day-to-day programming at the office.

答:
Perhaps looking into a keylogger would help. I've used PyKeyLogger before for simple logging, and it records a few other things besides keystrokes, such as mouse clicks, and screenshots. It has very verbose logging, so be prepared to parse/cleanup the resulting output.

Also, another suggestion. AutoHotKey. Amazing piece of software for all sorts of weird, strange automation and logging tasks. Might need a bit of work, though. But I would suggest going through their forums, and seeing if maybe someone can help you write something close to what you need, or teach you how to do it yourself.


答:
I think you have some misunderstandings about Reflective Practice and how it might apply to programming.

At it's simplest form, Reflective Practice is about reflecting upon a task after it has been completed.  Programming is not about typing, it's about thinking through a design and solving a problem in a programmatic fashion.  Typing is an after-effect of getting the design into the computer.

I don't think you'll learn all that much from watching what and where you were typing for a particular exercise.  Beyond a gross-level "oh yeah, I hadn't thought about that yet", I don't think there is that much information to be gleaned.  I think you would be better off taking many more notes during a particular problem / design session and then reviewing those notes against the end solution.  There are a number of exercise out there that will start you with a simple enough problem to solve, and then you start layering on additions.  Seeing how those designs hold up, reflecting upon your original thought process, and identifying areas to tweak will bring you more benefit.

Take a look into these P.SE posts for some additional thoughts on improving your skills.

Learn Programming Backwards

I am a not a good programmer

Title: Reflective practice in programming using keystroke playback

Body:
I'm thinking of applying Reflective Practice to improving my programming skills.  To that end, I want to be able to watch myself writing code.

In general, what is a good method for applying Reflective Practice to the craft of programming?

In particular, if it's a good idea, is there an editor that records keystrokes then plays them back at a later time - possibly running the keys together without delays, or replaying at a 2x/4x/8x accelerated rate?

Screencasting with RecordMyDesktop is an option, but has downsides of waiting for encoding and ending up with a big video file instead of a list of keystrokes.

Update: From "watching myself code" I expect to learn what kind of mistakes I make most frequently or where I waste time while coding. Then I can work on improving those aspects.  It could be certain formatting, syntax or runtime errors, or maybe long pauses that indicate I hadn't considered some issue before I started coding, or maybe I re-write entire functions because my initial design was wrong.  I understand that there's a lot more to programming than the act of writing code and this won't capture all of it.   As recommended I should make more design notes and reflect on those too.

Recording keystrokes may be more helpful to improving my technique in time-limited programming contests, and less helpful for improving day-to-day programming at the office.


问:
General programming techniques to speed up coding time
I am preparing for a programming contest where we have to code in C++ and it is all about producing working code in a short time. An example would be to use a macro to get the minimum of two ints or using memsets to initialize arrays (but I was told that you shouldn't use either here).

This leads to the question, what kind of coding techniques exist to use at a real job?

答: Review the standard libraries intensely, particularly the STL algorithms.  This will save you many lines of code and a lot of time.  The key to winning programming contests is in programming at as high a level as possible.  In C++, without external libraries, this means STL calls instead of for loops.  </p>


答:
If it's for an actual programming competition, don't use C++.  Use a fast, interactive, RAD scripting language.  This is something VB6 absolutely dominates at.  Go pre-armed with libraries you prewrote.  String splitting, array reversal, searching, sorting, rudementary graphics, console control.

If it's for work, do exactly the opposite.  Learn what's there, use a solid language (C++ is fine), comment everything, and so forth.  The two types of environments could not be farther apart.

Title: General programming techniques to speed up coding time

Body:
I am preparing for a programming contest where we have to code in C++ and it is all about producing working code in a short time. An example would be to use a macro to get the minimum of two ints or using memsets to initialize arrays (but I was told that you shouldn't use either here).

This leads to the question, what kind of coding techniques exist to use at a real job?


问:
iOS: Versioned static frameworks vs Git Submodules and included code
For the last couple of years I've been building static frameworks of common APIs for my iOS projects. I can build a universal binary containing all the architectures (i386, armv6, armv7) and wrap it up in a .framework directory structure. I then stored this in a directory based on the version of the framework. For example ..../myAPI/v0.1.0/myAPI.framework

Once I have this framework I can then easily add it to a project and if I want to advance the version, merely change the framework search paths to the later version.

This works, but the approach is very similar to what I would use in the Java world.

Recently I've been reading about using Git submodules and static framework sub projects in XCode 4.

Im wondering if my currently approach is something that I should consider retiring and what the pros/cons are of the new approach.

I'm weary of just including code because I've already had issues in a work project which had (effectively) multiple versions of a third party API.

Any opinions?

答:
You're really talking about two different things that just happen to solve approximately the same problem. Frameworks are all about deploying multiple versions of a library and associated resources while git is, of course, all about managing multiple versions of your source code. Those sort of amount to the same thing on iOS, where apps aren't allowed to dynamically link to third-party (i.e. non-Apple) frameworks.

So, you've been using frameworks to manage libraries for your app, and now you're thinking of using git submodules instead. Again, because you're not able to take advantage of dynamic linking, you should get about the same result either way. Given that, the main difference is that your workflow may change a bit.

Frameworks surely aren't going away on iOS -- if your current system works well for you, keep using it.


答:
The way to produce working code fast is to... slow down. Take very small steps. Make sure you know what each step is for. Make sure that after each step your code compiles and runs.

Best of all, use Test-Driven Development. Write a failing test.  Write just enough code to make the test pass. Refactor to make the code clean, making sure it still passes all the tests. Repeat.

If you do not do this, then it is very easy to write a big pile of code, which does not work.  Then it will take you a very long time to figure out why it does not work.


答:
Well, it sounds to me like you only know C and not C++ at all. These questions are easily answered by someone with a basic working knowledge of the language.

An example would be to use a macro to get the minimum of two ints

Just use a function? std::min already exists.

or using memsets to initialize arrays

std::array<T, N> already initializes it's contents.

what kind of coding techniques exist to use at a real job?

The first step is to know the language you are using.


问:
My software is hosted on a "bad" website. Can I do anything about it?
Edit: Thanks for all of the answers, guys! I think I'm just going to include some kind of text on my webpage telling users to only download from the links provided. The thing is that there have been some legitimate and illegitimate websites that have picked up on my software, so it would be safer just to tell users to avoid any website that I don't link to.

Thanks a lot for all the help!

Original:

The software I've created is hosted on what you could call a "bad" website. It's hard to explain, so I'll just provide an example.

I've made a free password generator. This, along with most of my other FREE software, is available on this website.

This is their description of my software:

```<code>Platform: 7/7 x64/Windows 2K/XP/2003/Vista
Size: 61.6 Mb
License: Trial
File Type: .7z
Last Updated: June 4th, 2011, 15:38 UTC
Avarage Download Speed: 6226 Kb/s
Last Week Downloads: 476
Toatal Downloads: 24908
</code>```

Not only is the size completely skewed, it is not trial software, it's free software. The thing is that it's not the description I'm worried about--it's the download links.

The website is a scam website. They apparently link to "cracks" and "keygens", but not only is that in itself illegal, they actually link to fake download websites that give you viruses and charge your credit card.

Just to list things that are wrong with this website: they claim all software is paid software then offer downloads for keygens and cracks; they fake all details about the program and any program reviews and ratings; they and the downloads site they link to are probably run by the same person, so they make money off of these lies.

I'm only a teenager with no means to pursue legal action. This means that, unfortunately, I can't do anything that will actually get results. I'd like my software to only be downloaded off my personal website. I have links to four legitimate locations to download my software and that's it.

Essentially, is there anything I can do about this? As I said above, I can't pursue legal action, but is there some way I can discourage traffic to that website by blacklisting it or something? Can I make a claim on MY website to only download my software from the links I provide? Or should I just pay no mind? Because, honestly, it's a bit of a ways back in Google results.

答: Unfortunately there is little you can do. I think you have the answers on your last paragraph.  As far as making claims on your web site about other sources - put an app signature on your site, explain than some "less than desirable" sites are listing your apps and it should only be downloaded from <here> or <here>. Do not name or provide any information about those sites - it opens you up for legal action (and raises their profile in Google). Most savy users will track the original source down. There is little you can do about others. Also be aware that 'your' app on their sites is probably your app plus extras - hence the need for a signature.


答:
You could place a self check in the program to check the size / hash of the executable to make sure it is the original binary you are distributing. I would recommend leaving that section out of the source code if you are distributing it in source form as it could cause problems for people legitimately adding on to the software.

maybe even implement this in the installer but that would be easy to get around.

Title: My software is hosted on a "bad" website. Can I do anything about it?

Body:
Edit: Thanks for all of the answers, guys! I think I'm just going to include some kind of text on my webpage telling users to only download from the links provided. The thing is that there have been some legitimate and illegitimate websites that have picked up on my software, so it would be safer just to tell users to avoid any website that I don't link to.

Thanks a lot for all the help!

Original:

The software I've created is hosted on what you could call a "bad" website. It's hard to explain, so I'll just provide an example.

I've made a free password generator. This, along with most of my other FREE software, is available on this website.

This is their description of my software:

```<code>Platform: 7/7 x64/Windows 2K/XP/2003/Vista
Size: 61.6 Mb
License: Trial
File Type: .7z
Last Updated: June 4th, 2011, 15:38 UTC
Avarage Download Speed: 6226 Kb/s
Last Week Downloads: 476
Toatal Downloads: 24908
</code>```

Not only is the size completely skewed, it is not trial software, it's free software. The thing is that it's not the description I'm worried about--it's the download links.

The website is a scam website. They apparently link to "cracks" and "keygens", but not only is that in itself illegal, they actually link to fake download websites that give you viruses and charge your credit card.

Just to list things that are wrong with this website: they claim all software is paid software then offer downloads for keygens and cracks; they fake all details about the program and any program reviews and ratings; they and the downloads site they link to are probably run by the same person, so they make money off of these lies.

I'm only a teenager with no means to pursue legal action. This means that, unfortunately, I can't do anything that will actually get results. I'd like my software to only be downloaded off my personal website. I have links to four legitimate locations to download my software and that's it.

Essentially, is there anything I can do about this? As I said above, I can't pursue legal action, but is there some way I can discourage traffic to that website by blacklisting it or something? Can I make a claim on MY website to only download my software from the links I provide? Or should I just pay no mind? Because, honestly, it's a bit of a ways back in Google results.


答:
Assuming the site is located in the US:

Consider a "DMCA takedown notice". (yes, google the direct term)  Spend some time researching the requirements, but you don't need an attorney to file the complaint.  The wikipedia article is a decent start.

There are sample letters that will serve your purposes.

You'll start with the offending website; they'll ignore you (most likely).

Go to the hosting company for the bad website.  They may or may not ignore you.

Keep going upstream from there.

There are some options you can take with Google and other search providers, but I'm not as familiar with those.  The above will help you research what to do.

To help in your hunt...  Network Solutions Whois is a site you can use to lookup domain registration.

Based upon that information, you may need to perform an ARIN / RIPE search to see who owns the block of IP addresses and is therefore going to be able to help you find the website provider.

Long term - put a link to the correct site in all of your applications.  About screens, splash screens, and wherever you can find screen real estate are places to consider.

K.Steff has some good points about the limits of what can be done.  You're not completely powerless, but you may not have all the options you wish you did.


答:
Think before you act. It's better to think and plan before writing a class implementation than after three failed ones. Also, think while you act - doing things in small steps greatly simplifies the development process.

Write only the code you need at the moment. That is, don't start off writing code with mentality like: "I'll need these functions later on so I might just aswell write their prototypes while I am at it". Things change, plans change. You'll end up with code which might not be even usable. It's waste of time.

Know what you're doing. There's nothing worse than trying to remember how basic functionalities and features of the language and/or library work. Get familiar with the tool(s) you use.


问:
Conflict resolution for two-way sync
How do you manage two-way synchronization between a 'main' database server and many 'secondary' servers, in particular conflict resolution, assuming a connection is not always available?

For example, I have a mobile app that uses CoreData as the 'database' on the iOS and I'd like to allow users to edit the contents without Internet connection. In the same time, this information is available on a website the devices will connect to. What do I do if/when the data on the two DB servers is in conflict?

(I refer to CoreData as a DB server, though I am aware it is something slightly different.)

Are there any general strategies for dealing with this sort of issue?
These are the options I can think of:

1. Always use the client-side data as higher-priority

2. Same for server-side

3. Try to resolve conflicts by marking each field's edit timestamp and taking the latest edit

Though I'm certain the 3rd option will open room for some devastating data corruption.

I'm aware that the CAP theorem concerns this, but I only want eventual consistency, so it doesn't rule it out completely, right?

Related question: Best practice patterns for two-way data synchronization. The second answer to this question says it probably can't be done.

答: This is the Byzantine Generals problem, which is unsolvable. You can never guaranteed synchronize the two servers if you cannot guarantee that at some time in the future, you will have sufficient reliable bandwidth to perform the synchronization all in one go.

Title: Conflict resolution for two-way sync


问:
Database Driven Web Application, C# Front-End and F# Back-End meaning
Hi I am an intern working with ASP.NET.

My current task is to make a website which will incorporate some jquery viewing features. This project seems to me will be primarily dealing with reading data from a database and making graphs out of them. This will require me to make custom queries from whatever the client is looking at. I think it is going to be what this guy calls an Ad Hoc Query tool

My plan for this is to make it a database-driven website. So I can utilize the jquery dynamic viewing capabilities. I stumbled upon the functional programming paradigm and found F#. I read that because of it's functional programming paradigm, it makes it a good language to do asynchronous functions. I read about how you can use this with  LINQ to SQL and how easy it is to make queries without actually putting the query language in. I understand the concept of the MVC design pattern.

But I don't understand what they mean about C# being the front-end and F# being the back-end. Can someone clarify this to me? Also what are your thoughts about doing this project in this way? Any comments and thoughts are greatly appreciated. I feel as if learning F# will be a great learning experience for me.

My guess is that the F# back-end is like the part where it controls the calls to the database. F# is possibly the model part of the design pattern. And C# is the controller. So HTML, Javascript and Jquery stuff will be my View design pattern. Clarify please?

答:
This article expresses the front end as the "Views", and the back-end as the "models", with the controller being the glue between them. In actuality, this article's example uses F# for the controllers and models, and C# (and the "Razor" template) for the views (IOW, rendering the html).

As for how well this solution works: this is a pretty subjective question. You really should look to who will be working on the project and planning around their strengths, as the majority of times I've found that the stumbling blocks are not the pros and cons of various technologies but the ability for the developers to understand the technologies being used. Perhaps an all C# solution will be more beneficial for a new project?

While F# does have a nice idea in asynchronous workflows, do you really need it? If you're making a website from scratch, my guess is you don't know yet, so you should go with a simple solution first. On the other hand, if you have people who know F# (or other functional languages) already, then sure, check out the solution mentioned in the article.

OwnerDisplayName: Mark Hildreth


答:
Finding and complaining to their hosting provider is the place to start DMCA complaints are only legally binding in the US but hosting providers in other western countries tend to take them seriously as well. </p>

<p>Failing that work your way up the hosting chain as far as possible. Data centers and upstream providers do not like to deal with complaints regardless of the country. No one wants to be associated with viruses and adware. </p>

Body:
Finding and complaining to their hosting provider is the place to start DMCA complaints are only legally binding in the US but hosting providers in other western countries tend to take them seriously as well.

Failing that work your way up the hosting chain as far as possible. Data centers and upstream providers do not like to deal with complaints regardless of the country. No one wants to be associated with viruses and adware.


问:
Are my negative internship experiences representative of the real world?
I'm curious if my current experiences as an intern are representative of actual industry.

As background, I'm through the better part of two computing majors and a math major at a major university; I've aced every class and adored all of them, so I'd like to think that I'm not terrible at programming. I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code. Comments don't exist, it's all spaghetti code, and everything that could be wrong is even worse. I've done a ton of tutoring/TAing, so I'm very used to reading bad code, but the major industry products I've been seeing trump all of that. I work 10-12 hours a day and never feel like I'm getting anywhere, because it's endless hours of trying to figure out an undocumented API or determine the behavior of some other part of the (completely undocumented) product. I've left work hating the job every day so far, and I desperately want to know if this is what is in store for the rest of my life.

Did I draw a short straw on internships (the absurdly large paychecks imply that it's not a low quality position), or is this what the real world is like?

答: It's hard to tell what you consider horribly low quality code, but yeah few programmers are very good (by definition). As software evolves, people make mistakes. Over time these build up, and business pressure (and programmer laziness/ignorance) makes refactoring... Uncommon.</p>


答:
There is lots of opinions about this because everyone's experiences are different.

Mine are that about half the developers I encounter are well intentioned, but of average ability. There is a small group of brilliant people at the top, and a small group at the bottom who are trying but basically should do something else because they don't really get it. Unfortunately there is also another small group of incompetent fools who think they are way cleverer than everyone else and are usually quite in your face about how you should be following them.

Project wise, I've gone into a lot of jobs and immediately been asked to "look after" some established project, usually one that the business has just discovered it really needs after loosing the last developer on it. I usually find exactly what you have outlined above - undocumented, over-engineered, buggy spaghetti. Sometimes I can fix it, sometimes I just start again. It doesn't even need to be old code, I've found this on new projects I've been asked to "help out" on as well.

You have to take heart from the fact that most companies are going to give interns the crappy jobs. The fun ones come after you have done two things: 1 - proven yourself and 2 - made some time to work on things other than fixing other people's mistakes. In other words you have to show ability and initiative.

The real trick to handling bad code is figuring out what is salvageable and what is not. This comes from experience and research.

The other career option you have is to stop working for established companies and look to work in startups. Then there will be no crap legacy code to maintain so you will have the chance to help build something better. The downside is that the pressure to deliver placed on startup projects often means that shortcuts and hacks are used when they should not be.

Programmers are all too often willing to take on tech debt in order to deliver early or on time. Unfortunately the impact of this tech debt is often glossed over, minimized, ignored or dismissed by the developers and management until it's too late and they are in trouble.

Sorry if this sounds depressing. I'm sure someone else can do a more positive piece. :-)

Title: Are my negative internship experiences representative of the real world?

Body:
I'm curious if my current experiences as an intern are representative of actual industry.

As background, I'm through the better part of two computing majors and a math major at a major university; I've aced every class and adored all of them, so I'd like to think that I'm not terrible at programming. I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code. Comments don't exist, it's all spaghetti code, and everything that could be wrong is even worse. I've done a ton of tutoring/TAing, so I'm very used to reading bad code, but the major industry products I've been seeing trump all of that. I work 10-12 hours a day and never feel like I'm getting anywhere, because it's endless hours of trying to figure out an undocumented API or determine the behavior of some other part of the (completely undocumented) product. I've left work hating the job every day so far, and I desperately want to know if this is what is in store for the rest of my life.

Did I draw a short straw on internships (the absurdly large paychecks imply that it's not a low quality position), or is this what the real world is like?


答: The database is IMO the only place where DRY can be violated, because if something bypasses your ORM and has bad data, that's it. Game Over. Having corrupt data is the killing blow. </p>

Title: For an ORM supporting data validation, should constraints be enforced in the database as well?

Body:
I have always applied constraints at the database level in addition to my (ActiveRecord) models. But I've been wondering if this is really required?

A little background

I recently had to unit test a basic automated timestamp generation method for a model. Normally, the test would create an instance of the model and save it without validation. But there are other required fields that aren't nullable at the in the table definition, meaning I cant save the instance even if I skip the ActiveRecord validation. So I'm thinking if I should remove such constraints from the db itself, and let the ORM handle them?

Possible advantages if I skip constraints in db, imo -

Can modify a validation rule in the model, without having to migrate
the database.

Can skip validation in testing.

Possible disadvantage?

If its possible that ORM validation fails or is bypassed, howsoever, the database does not check for constraints.

What do you think?

EDIT In this case, I'm using the Yii Framework, which generates the model from the database, hence database rules are generated also (though I could always write them post-generation myself too).


答:
After 25 years and a variety of companies and industries I can say:

Yes, it's pretty common.

This is why engineers are paid pretty well usually, they have to be good at encountering messy hodge-podges and still be able to make changes while resisting the pressing desire to refactor the whole damn thing and find out what the hell it's really supposed to be doing.  I threw the emotion in for you there - it's normal to feel that way about the code you encounter!

The code you see will often have gone through endless iterations by different programmers with different approaches and standards and different naming conventions, etc. etc.

What happens though is that the $ pressure is always on.  It's always tempting to describe how and why better code is the only way in the long-term but in a great deal of jobs the clock is ticking for a short-term quick-fix solution.  It only takes 1 engineer a short time to destroy standards in a project.  It takes a very good manager that knows how to prevent this and defend the right approach (when reasonably possible) to really address it.

One thing is for sure, the term 'good code' is just too subjective to be useful.  It's not subjective to you of course, you can list the specific reasons / items.  However other people list different items and priorities, some not even technical, that they think are important, and thus it's subjective.

Like Drekka, this is starting to sounds depressing, so let me try to turn a little more positive, because it's certainly true that:-

There are organizations, often ones with the largest technical components that are doing the right things.

The newer the company... and the code... the cleaner it tends to be.  spaghetti grows due to time and people.

Some folks do TDD and BDD, others don't.  The range is huge.

After about 10 years, currently, the entire technology base changes so those who stay in the industry can have as hard a time keeping up as do newbies.

Finally, as Anthony Blake points out, there are always 3 factors - time, cost and quality.

I like the related expression:  "pick 2" !


答:
They call it the Real World™ for a reason.

99% of what you will encounter in the real corporate world will be considered crap, and for good reason that I will explain. The 1% that isn't considered crap will become crap eventually.

#1 Write Code, #2 ????, #3 Profit!

First off businesses exist to turn a profit, they do not exist to generate mountains of perfectly theoretically clean designed and pristine academic code housed in golden repositories of perfectness. Not even close, not even the ones in the business of selling source code they produce.

In the business world code is a means to an end. If some code solves a business problem and makes more money than it costs to create and maintain then it is desirable for the business. Employing you to write code is just one way for the business to obtain code.

Theory 0 - Practice ∞

Ideally maintenance should be more of a concern but it usually isn't, because in the short term it doesn't win out financially. In the long term, software usually has a relatively short life cycle, especially web based applications, they get obsoleted quickly and re-written more often.

In house line of business applications are the ones that churn on as what are perceived as endless zombie projects because of many momentum based reasons. These projects are actually successes they continue because they continue making the business a profit.

In theory there is no difference between theory and practice. In
  practice there is. - Yogi Berra

In theory perfectly architected absolutely clean pristine code bases with 100% code coverages should save companies money, in practice it doesn't even come close to delivering any thing close to a valid return on investment.

Physics of the Software Lifecycle

There is also a super powerful entropy force at work in the world of software. It is a black hole of inevitability that condemns all software to degenerate into a Big Ball of Mud.

The farther you start from a BBM the better, but every software system will eventually get there given enough time. How quickly you approach 100% entropy is determined by where you start and how rapidly you pile on technical debt and how high the interest on it is.

Software systems degenerate and rot because of maintenance, not because of the lack of it. A system that is in place for years with no code changes by definition meets all its requirements and goals and is a success.

It is the systems that require constant change because they started out closer to maximum entropy are the ones that are constantly poked and prodded and it is the maintenance that accelerates the negative change.

Good Enough is Good Enough

Short lifecycle systems like websites that change constantly don't benefit from expensive huge upfront design 100% code coverage in unit tests, because the amortization time is too short to recoupe the costs.

Long lifecycle systems like the above mentioned internal line of business apps, don't really benefit from massive investments of 100% code coverage unit tests either, because the rate of change over the life of the project approaches a constant that is near zero in a non-linear fashion.

That is why end of life plans are more important and replacement systems should be planned just as something is being released, not when it has passed it prime by a few years and unsupportable so a new system must be rushed into place.

They don't teach about BBM as far as I know, I have never encountered a recent CS graduate that knew what it was, much less why it happens.

That is why Good Enough is Good Enough, anything more or less isn't.

Software Slumlords

There are real estate slum lords for a reason, they make a profit on the run down shanty buildings they own. The make more profit than they spend on incremental maintenance of the run down property. If they didn't they would tear down the building and replace it. But they don't, because the incremental costs are far less than overhauling or replacing the entire building. There are also customers ( tenants ) that are willing to pay for run down property.

No building owner, slum lord or not is going to spend money on a property just because of some academic notion of perfection that doesn't translate to a substantial profit over the associated cost.

No customer is going to pay for upgrades to a software system that is working acceptably to them. No business is going to spend money on just writing and re-writing code for no tangible substantial profit.

Microsoft is most dominate and successful software slumlord there is. Windows did not start getting major foundational re-writes until very recently. And they still haven't dropped all the legacy code from the kernel. It doesn't make business sense to them, people are more than willing to accept the low bar of expectations they have set over the last decade.

Prognosis

This has been a pattern for the 20+ years I have been in software development. It isn't going to change any time soon. This isn't the way people want it to be out of some belief system, it is a reality of external forces on a business. Business drives decision making, profits aren't evil they pay your salary, short term or long term vision is irrelevant, this is a short term industry of constant change by definition. Anyone that argues against good enough to make a profit doesn't understand business.

I spent 15 years consulting and learned very quickly that good enough was just that, anything else was costing me money. Yeah I wanted things to be perfect, but unless you are selling a code base, which 99.99999% of the time you are selling a solution, all that prefect clean organized elegant code is lost and you just wasted your time you will never get reimbursed for.

Progress and Hope

Agile methodologies are a good step in the right direction, at least philosophically. They address the chaos and constant change as a first class citizen and accept it. They reject dogmatic practices, acknowledging that the methodologies and practices should change as well as the requirements and technologies.

They accept the entropy that is introduced by the lack of time or changing requirements, changing staff and the liveness of a software system with the concept of technical debt.

But Agile isn't a panacea, it isn't going to change the fundamental laws of physics and code bases will rot regardless. It is up to management to plan on dealing with the rot before it gets completely out of hand and un-manageable.

Agile when done correctly, helps manage the entropy, slow it down, track it, measure it and deal with it in a planned manner. It won't stop it!

Career Decision

If this is a real philosophical problem for you, you should probably consider other career choices, because the way things work has valid business merit behind it. Open Source projects don't have any better track record, and in many cases the code is even worse than most corporate code I have seen.


答:
I participate regularly in ACM competitions, hopefully some of these tips will help you:

As others said, familiarize yourself with the language, in C++ especially the STL, it has both common functions that you'd want to use (binary_search, min, max) and robust data structures to save you time (stack to avoid straight up recursion, queue for BFS, even priority_queue for Dijkstra if you like it that way).

Identify the category of the problem, if it's mathematical, dynamic programming, graph theory, etc. Ask yourself: How familiar are you with that type of problem? After doing this, you should make decisions regarding the order on which you'll solve them, which goes hand to hand with the next point...

You want to understand the problem completely before typing, solve the right problem, in my first competitions I thought that if I wasn't typing I was wasting my time; I later found that this was a mistake.

Don't think comments are a waste of time, at least in "clever" code, you don't want to go debugging line-by-line to see what went wrong (that is a real waste of time), value clarity.

Have fun.


答:
I'm curious if my current experiences as an intern are representative of actual industry.

No it is not. It is representative of your career level and experience. It's all part of learning about how businesses work from an internal quality control perspective.

As background, I'm through the better part of two computing majors and a math major at a major university; I've aced every class and adored all of them, so I'd like to think that I'm not terrible at programming. I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code.

Your skills, your experience, your education has no impact on the quality of work done by others. Simply because you don't have the authority to change those practices. It doesn't matter if you were good or bad in university. That doesn't change how the company you work for currently operates. So while it's great you have all this background. It's really for your own benefit and not theirs. That's why it's important to study what you love.

I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code. Comments don't exist, it's all spaghetti code, and everything that could be wrong is even worse. I've done a ton of tutoring/TAing, so I'm very used to reading bad code, but the major industry products I've been seeing trump all of that.

What I have learned in my many years of programming is that there is a difference between "quality of code" and "acceptable code". The truth is that either someone with authority finds the source code in acceptable condition, or they find it unacceptable but necessary. While it would be nice if we could all clean up the projects we get involved in. It's often not in the businesses interest or budget to allocate resources to do that work. Logical arguments can be made until the sun rises the next day why this would be a good thing to fix, but when management has decided the current state is "acceptable" then little can be done. It is all directly related to who runs things. Either they value good internal quality or they do not. You clearly value it and therefore this current state bothers you.

You will find examples of this type of problem in any industry that depends on internal quality control. Ranging from software development to manufacturing. You need to learn to see this not as a problem, but simply as the current condition of their source code. This is how it is, it takes X number of minutes to find something, it takes X number of minutes to fix something.

The business either doesn't care about this extra time, or it finds it acceptable.

I work 10-12 hours a day and never feel like I'm getting anywhere, because it's endless hours of trying to figure out an undocumented API or determine the behavior of some other part of the (completely undocumented) product. I've left work hating the job every day so far, and I desperately want to know if this is what is in store for the rest of my life.

Why was it acceptable for you to put in long hours in university to study a subject, but now it is not acceptable to put in long hours to study source code? I'm sure the reason the employer hired you was because they thought you could handle it.

Let me give you some advise. Good developers know when to ask for help from their follow teammates. Don't think the answers are always in the code. I've saved myself hours of time by simply asking people a few questions. Sounds like you need some help coming up to speed.

Secondly, we don't know the work conditions. Working long hours is a fact of life in so many industries. That you need to resolve on your own, but I can tell you. Hating your job is never a good sign. You should deal with that feeling and get to the root of it. I'm sorry that you find this experience negative.

Did I draw a short straw on internships (the absurdly large paychecks imply that it's not a low quality position), or is this what the real world is like?

You were doing very well in school, but now you have an internship and you're not doing so well. Sounds like you're already in the real world. That's part of life. The question is, what are you going to do about it? That my friend, is the only thing that matters. We can't tell you what to do. You have to make up your own mind.

I can tell you that it sounds like your experience at your age was far better then any opportunities that I had. Life for me in the 90's was a struggle to pay rent and find my next contract. Consider yourself lucky.


答:
I know this has been answered, but...

I have always used a PAD file and this way I can change my software
  listing on shareware sites.

See here:  http://www.appointmentsbook.com/appointmentsbook/pad_AppsBookpro.xml


问:
What is So Unique About Node.js?
Recently there has been a lot of praise for Node.js.  I am not a developer that has had much exposure to network application.  From my bare understanding of Nodes.js, its strength is: we have only one thread handling multiple connections, providing an event-based architecture.

However, for example in Java, I can create only one thread using NIO/AIO (which is non-blocking APIs from my bare understanding), and handle multiple connections using that thread, and I provide an event-based architecture to implement the data handling logic (shouldn't be that difficult by providing some callback etc.)?

Given JVM being a even more mature VM than V8 (I expect it to run faster too), and event-based handling architecture seems to be something not difficult to create,  I am not sure why Node.js is attracting so much attention.  Did I miss some important points?

答:
The three main reasons I would give are:

Non Blocking IO / Asynchronous IO. This is hashed everywhere on the web and in the previous posters. One thing I would contribute is that designing your code to explicitly assume asynchronous behaviours assists the compiler engine to maximize the hardware. Yes, many of the JIT compilers and hyperthreading processors take synchronous code and help parallelize the execution. This of course is a best effort approach. In contrast, explicitly building the application for async io you ensure the engine and the hardware can maximize the execution time for your code. Admittedly, I don't have quantifiable data to prove this, but it makes me feel warm inside to think this way.

Single code base for client and server. This has a number of advantages: help optimize datacenter costs by being able to move business logic from the server to the client; help reuse business logic / data validation; reduce the complexity of developer skills that need to exist to support the product (vs. Python & javascript).

Low barrier to entry. In many ways Javascirpt is like Basic, Pascal and Perl of yester-year. It is super easy to start writing code and does not require a lot of domain knowledge to get going. This also helps reduce your development costs by being able to bring in more jr developers and getting the ramped up on a project. [Of course you need to get past the ideologues who believe programming languages should be difficult in order to weed out the low functioning developers]

Title: What is So Unique About Node.js?


问:
How to define a natural id in database?
There are a lot of manuals. I am trying to create an database to hold information of these documents. But, there is a small problem.

How can I give meaningful id to the manuals? Are there any standard or logic behind the giving meaningful id to the documents? If there is no standard, can you tell me how I should do that?

example:

```<code> table :

         manual id | manual name
</code>```

EDIT:

```<code>Not Meaningful ID

     1        or  M1        or   foo
     2            C2             bar
     3            P123           name
    ...           ...            ...
     (i)          (ii)            (iii)
</code>```

(i) Not meaningful for me because if some item deleted, there can be gap. ex 1 33 100.

(ii) random character can be confusing when one try to give a name to new manual

(iii) Why giving name is not preferred is because finding a name to the manual as ID is hard after 500 manuals.

Meaningful :

New ID

```<code>* Can be easily produced even if after 1000 manuals
* Should not be so complicated
</code>```

答:
What's the problem with gaps in your database when using IDs from 1 to n?
If you really mind the gaps, you could add new manuals inside those. (In your example the next new manual would get the ID 2, 3, ... , 32, 34).
Or you could save a list/stack of the IDs from the deleted manuals and every time you add a new you pop the next ID from the list/stack. This would save you some time.

Also, an ID is not meant to be meaningful, it's just to have a fast way to distinguish between different manuals, so IDs should be unique.
You said every manual has a name which should be pretty meaningful already and if two manuals have the same name they at least have different IDs.

Title: How to define a natural id in database?


答:
Usually, one might first try to find a natural key, coming from the problem domain; e.g. an EAN/UPC code for products or the SSN for people.

When there is no obvious natural key, the artificial ID is just a number counting up, and those gaps after deleting are not considered problematic, because the ID is meaningless anyway.

Hint: Meaningfulness cannot be created artificially.

Title: How to define a natural id in database?

Body:
There are a lot of manuals. I am trying to create an database to hold information of these documents. But, there is a small problem.

How can I give meaningful id to the manuals? Are there any standard or logic behind the giving meaningful id to the documents? If there is no standard, can you tell me how I should do that?

example:

```<code> table :

         manual id | manual name
</code>```

EDIT:

```<code>Not Meaningful ID

     1        or  M1        or   foo
     2            C2             bar
     3            P123           name
    ...           ...            ...
     (i)          (ii)            (iii)
</code>```

(i) Not meaningful for me because if some item deleted, there can be gap. ex 1 33 100.

(ii) random character can be confusing when one try to give a name to new manual

(iii) Why giving name is not preferred is because finding a name to the manual as ID is hard after 500 manuals.

Meaningful :

New ID

```<code>* Can be easily produced even if after 1000 manuals
* Should not be so complicated
</code>```


答:
There are some great answers here, but let me add my bit;

Welcome to the real world - unfortunately this is very common.

Refer to the diagram below;

With corporate software, you can only pick 2 or the above, and you must sacrifice one.

As you seem to have discovered, the majority of the corporate world go with speed and price.