Classes and Objects

Started by
10 comments, last by alvaro 10 years, 1 month ago

Hey, I'm all new to classes, and I've done the best I could.

How could I go by making this code better?

Main.cpp:

http://pastebin.com/JX2HPXtG

itemClass.cpp:

http://pastebin.com/2qZDZtit

itemClass.h:

http://pastebin.com/Hhd9PziW

monsterClass.cpp:

http://pastebin.com/ZVJ2KDbV

monsterClass.h:

http://pastebin.com/3wbXkb61

playerClass.cpp:

http://pastebin.com/cdhFhyA4

playerClass.h:

http://pastebin.com/Tk1B5aJr

Any help is much appreciated !

Regards,

Matias.

Advertisement

Those classes looks like a good start.

The first thing I'd ask you to think about is the class suffix. For example, std::string is a class but it isn't called std::stringClass. Consider simple class names like "player", "monster" and "item". A common convention is to use Uppercase for class names, so Player - and lowercase for function and variable names, so "Player player" or "Monster pig".

The next thing to think about is maybe using constructors instead of having setters for all the fields. One problem with adding setters is that it can break encapsulation and defeat the purpose of making all the fields private.

Also, consider adding member functions for interesting properties that aren't exactly fields. For example, you're checking if a monster is alive by testing whether it's HP is greater than zero. You can encapsulate this logic by adding a member function, bool isAlive(), and then the client code doesn't need to worry about the Monster's HP directly.

Those classes looks like a good start.

The first thing I'd ask you to think about is the class suffix. For example, std::string is a class but it isn't called std::stringClass. Consider simple class names like "player", "monster" and "item". A common convention is to use Uppercase for class names, so Player - and lowercase for function and variable names, so "Player player" or "Monster pig".

The next thing to think about is maybe using constructors instead of having setters for all the fields. One problem with adding setters is that it can break encapsulation and defeat the purpose of making all the fields private.

Also, consider adding member functions for interesting properties that aren't exactly fields. For example, you're checking if a monster is alive by testing whether it's HP is greater than zero. You can encapsulate this logic by adding a member function, bool isAlive(), and then the client code doesn't need to worry about the Monster's HP directly.

Thank you so much for the advice.

I would think that the function bool isAlive is really useful, but how would I go by adding it to the program? Perhaps in the monster class? Or what would be better?

Also what exactly do you mean by constructors?

I am not going to read a whole bunch of beginner's code just for fun, but I did look at your Main.cpp. The obvious thing that can be improved is readability. You have a bunch of comments that would not be needed if your variables had descriptive names. So instead of
        //Temporary Name Holder
        string x;
        //Choice
        int c;
        //Random Monster Selection
        int v;
        //Temporary damage
        int attack;
you could have
  string tmp_name_holder;
  int choice;
  int random_monster_selection;
  int tmp_damage_from_attack;
More things:
* It's best to declare variables at the first point where they are needed. That will provide the reader the context to understand what the descriptive name means. And yes, you should think of your code as something that people read.
* Don't repeat yourself. There are 4 nearly-identical blocks in the code that handles attacking a monster. Those should only be one block that can work with any of the monsters. This would be easier to do if the monsters were contained in an array instead of being 4 separate variables.
* Including a file called "Includes.h" is a generally a bad idea. It won't matter for a program of this size, but the point of this exercise is learning good practices. So think of what dependencies you really have and include those. Otherwise, all of your code will depend on all of your other code and you will have to recompile all of your code whenever anything changes. In my project at work, full recompilation takes 15 minutes, and that's with a parallel compilation that devotes 10 processes to it.

OK, I did look through some of the other files. Your classes are mostly just holders for data, which probably means you are not thinking in terms of what operations you want to support on them, kind of missing the point of objects and classes. Also, some of your methods have surprising semantics:
void playerClass::setGold(int gold)
{
        playerClass::gold += gold;
}
Why does `setGold' add to the amount of gold instead of setting it to the value I just passed? How about calling it `addGold' instead?

I am not going to read a whole bunch of beginner's code just for fun, but I did look at your Main.cpp. The obvious thing that can be improved is readability. You have a bunch of comments that would not be needed if your variables had descriptive names. So instead of


        //Temporary Name Holder
        string x;
        //Choice
        int c;
        //Random Monster Selection
        int v;
        //Temporary damage
        int attack;
you could have

  string tmp_name_holder;
  int choice;
  int random_monster_selection;
  int tmp_damage_from_attack;
More things:
* It's best to declare variables at the first point where they are needed. That will provide the reader the context to understand what the descriptive name means. And yes, you should think of your code as something that people read.
* Don't repeat yourself. There are 4 nearly-identical blocks in the code that handles attacking a monster. Those should only be one block that can work with any of the monsters. This would be easier to do if the monsters were contained in an array instead of being 4 separate variables.
* Including a file called "Includes.h" is a generally a bad idea. It won't matter for a program of this size, but the point of this exercise is learning good practices. So think of what dependencies you really have and include those. Otherwise, all of your code will depend on all of your other code and you will have to recompile all of your code whenever anything changes. In my project at work, full recompilation takes 15 minutes, and that's with a parallel compilation that devotes 10 processes to it.

OK, I did look through some of the other files. Your classes are mostly just holders for data, which probably means you are not thinking in terms of what operations you want to support on them, kind of missing the point of objects and classes. Also, some of your methods have surprising semantics:

void playerClass::setGold(int gold)
{
        playerClass::gold += gold;
}
Why does `setGold' add to the amount of gold instead of setting it to the value I just passed? How about calling it `addGold' instead?

Hello, first I would like to thank you, for your advice on the variable names and positions.

I don't really know how to work arrays, I can't seem to get it working, but perhaps you or someone on here could give me a general idea on how to place it all in one block instead of 4?

Yeah, I've heard that Includes.h is a bad idea, it was also just something I added to make it a little easier while practising ;)

About the setGold, at the time of creation I couldn't put my tongue on the word "add" for some reason ;P (I'm Danish)

Changed it to addGold. Thank you;)

Those classes looks like a good start.

The first thing I'd ask you to think about is the class suffix. For example, std::string is a class but it isn't called std::stringClass. Consider simple class names like "player", "monster" and "item". A common convention is to use Uppercase for class names, so Player - and lowercase for function and variable names, so "Player player" or "Monster pig".

The next thing to think about is maybe using constructors instead of having setters for all the fields. One problem with adding setters is that it can break encapsulation and defeat the purpose of making all the fields private.

Also, consider adding member functions for interesting properties that aren't exactly fields. For example, you're checking if a monster is alive by testing whether it's HP is greater than zero. You can encapsulate this logic by adding a member function, bool isAlive(), and then the client code doesn't need to worry about the Monster's HP directly.

Thank you so much for the advice.

I would think that the function bool isAlive is really useful, but how would I go by adding it to the program? Perhaps in the monster class? Or what would be better?

Also what exactly do you mean by constructors?

In a couple places (e.g., monsterClass), you have empty constructors, and an instance is initialized by (e.g.) setMonster.

You may want to consider setting default values in the constructor. Otherwise, if you create a monster and either forget to initialize it, or access it before it's initialized, you may get some strange behavior: e.g., you call getHP before hitpoints has been set. Don't assume that all values will be initialized to 0 (or to any particular value).


// Constructor - set default parameters
monsterClass::monsterClass(void)
{
    monsterClass::name = "<unnamed>";
    monsterClass::hitpoints = 20;
    monsterClass::experience = 10;
    monsterClass::gold = 10;
    monsterClass::damage = 0;
}


Seconding Alvaro's suggestion to name variables with descriptive names: it may seem like you're going to be doing a lot of typing, but, if you use an IDE like Visual Studio with intellisense, as you begin typing a variable name, a dropdown list of possible completions will shorten the process AND, by selecting from the dropdown, you'll ensure the spelling is correct. It will be worth the effort.

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

In a couple places (e.g., monsterClass), you have empty constructors, and an instance is initialized by (e.g.) setMonster.

You may want to consider setting default values in the constructor. Otherwise, if you create a monster and either forget to initialize it, or access it before it's initialized, you may get some strange behavior: e.g., you call getHP before hitpoints has been set. Don't assume that all values will be initialized to 0 (or to any particular value).


// Constructor - set default parameters
monsterClass::monsterClass(void)
{
    monsterClass::name = "<unnamed>";
    monsterClass::hitpoints = 20;
    monsterClass::experience = 10;
    monsterClass::gold = 10;
    monsterClass::damage = 0;
}

Seconding Alvaro's suggestion to name variables with descriptive names: it may seem like you're going to be doing a lot of typing, but, if you use an IDE like Visual Studio with intellisense, as you begin typing a variable name, a dropdown list of possible completions will shorten the process AND, by selecting from the dropdown, you'll ensure the spelling is correct. It will be worth the effort.

Oh yes, I see. I will start doing this.

However, like Alvaro said

"* Don't repeat yourself. There are 4 nearly-identical blocks in the code that handles attacking a monster. Those should only be one block that can work with any of the monsters. This would be easier to do if the monsters were contained in an array instead of being 4 separate variables."

How can I go by doing this?

A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...


void attackMonster(monsterClass& monster)
{
    monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
    // .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}


Then:

attackMonster(pig);

attackMonster(some-other-instantiated-monster);

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...


void attackMonster(monsterClass& monster)
{
    monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
    // .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}

Then:

attackMonster(pig);

attackMonster(some-other-instantiated-monster);

So I should be creating an attackMonster class and make a function that I can call in main like attackMonster(pig) and it would attack the pig?

A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...


void attackMonster(monsterClass& monster)
{
    monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
    // .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}

Then:

attackMonster(pig);

attackMonster(some-other-instantiated-monster);

So I should be creating an attackMonster class and make a function that I can call in main like attackMonster(pig) and it would attack the pig?

No, attackMonster is a function, not a class. Different concepts.

About the idea of using an array of monsters, first I have to understand what your code is doing. You have a notion of what a pig is, which is something with 5 hit points, 5 for stamina, an amount of gold between 1 and 5 and a random damage between 0 and 0 (???). If that's the case, I would create a class MonsterType which contains those parameters that can be used to create a specific pig. Then you can have an array of MonsterType objects, which I would call `bestiary'.

int random_in_range(int min, int max) {
  return min + std::rand() % (max - min + 1);
}

class MonsterType {
  std::string name;
  int hitpoints;
  int experience;
  int min_gold;
  int max_gold;
  int min_damage;
  int max_damage;

  MonsterType(std::string name, int hitpoints, int experience, int min_gold, int max_gold, int min_damage, int max_damage)
    : name(name),
      hitpoints(hitpoints),
      experience(experience),
      min_gold(min_gold),
      max_gold(max_gold),
      min_damage(min_damage),
      max_damage(max_damage) {
  }

  Monster create_instance() const {
    return Monster(name,
                   hitpoints,
                   experience,
                   random_in_range(min_gold, max_gold),
                   random_in_range(min_damage, max_damage));
  }
};

// [...] somewhere in Main.cpp                                                                                                        
  MonsterType const bestiary[4] = {
    MonsterType("Pig", 5, 5, 1, 5, 0, 0),
    MonsterType("Blob", 7, 5, 4, 15, 0, 1),
    MonsterType("Goat", 10, 7, 4, 18, 0, 2),
    MonsterType("Sheep", 20, 22, 7, 26, 0, 3)
  };
 
  // [...]
 
  int random_bestiary_index = std::rand() % 4;
  Monster monster = bestiary[random_bestiary_index].create_instance();
  while (monster.isAlive() && player.isAlive()) {
    // Here goes your single copy of the loop
    // [...]
  }

This topic is closed to new replies.

Advertisement