开发者

Rails organizing code

i happen to be kinda picky when programming something big. I try to find the best way to do it it terms of speed and complexity. Since i've been learning Rails the previous 3 months, i try to find the best techniques for everything. I would like to ask you how you would go about writing some code like this :

@defender = User.find_by_id(user_id)
@attacker = current_user.clone
@attacker_starting_attribs = current_user
@defender_starting_attribs = @defender.clone
@defenderWeapon = @defender.getEquippedWeapon
@attackerWeapon = @attacker.getEquippedWeapon
@combat = Combatant.fight(@attacker, @defender)

This code is about the battle outcome between two persons in a browser game. The code works well, but i've some problems in terms of good coding. In fact, i know that my code is bad here, that's why i ask you what a better version would be. Let me explain what happens in开发者_如何学C this code.

@defender is given by user_id, so i guess that this part is needed. Now, in @attacker i'm cloning the current_user. The reason is that Rails works on objects and current_user will be changed inside Combatant.fight. I need both the new hp and the old hp and that is why i'm cloning the object. The defender and attacker starting attribs illustrate that concept. Now, i get the weapons in instance variables, so that i can get their information inside the final view.

However, the weapons are needed inside the fight function and i execute the same getEquippedWeapon twice again inside fight(). I was not so comfortable with something like fight(@attacker, @defender, @attacker_weapon, @defender_weapon), but i don't also like the idea of repetition. So, i would like an opinion on that.

@combat is a hash containing the result of the combat. Fight happens and i get that hash back in the view.

I'm not pleased with my coding on that stage and i want your opinion. How would you do it ? Is there maybe a design pattern for that ? Please tell me your opinion.

Thanx :)


I'm finding it difficult to completely understand what you're trying to do. I get the gist of it though (2 people fighting). I won't be able to provide an answer yet, but hopefully this gets the ball rolling:

From the code you provided, @attacker_starting_attribs and @defender_starting_attribs aren't being used.

As far as "good techniques", I try to stay as OO as possible. Instead of Combatant.fight(@attacker, @defender), I would do @attacker.fight(@defender)

As a ruby convention, method names are underscored. In your case, .get_equipped_weapon instead of .getEquippedWeapon, or even better .equipped_weapon.

Anyways, I bet if you provided more code, you'd get more answers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜