Code is getting convoluted

I’m working on a game and the code is quickly getting convoluted. I know it’s because I don’t have good coding habits, but I’m pretty new at game programming so what I have is the only solution that I can come up with. How should I go about cleaning it up? It’s coming to the point that making any progress is a daunting task due to the amount of back tracing I need to do in my own code just to get the variable or desired behavior.

I’m not really sure how to clean it up because if I re-look at everything again, I’m just going to want to do it the exact same way because that’s how it makes sense to me. Anyone else run into this problem? How did you get through it?

When I am coding, I always comment and java-doc my code. That helps a lot. Also, if you are developing a big game, then create packages for different parts of the game :slight_smile:

man, but if instead to put in your mind how u write the code, you try to remember what are the block and how is logically composed your code?
I mean the software architecture exist because if u have to write 10000 or more line of code in this way, it is impossible to manage! or to remember where is the code that dosomething.
try at list to separate the stuff by duty using the packages and the position of the class automatically will be at list organize

and make at list to minimize the effort of reorganize the code, to separate:
logic that make the draw in the windows
logic that make update
technical stuff in the beginning to draw create windows input listener etc

try to do time, you will see what are the advantages!
if u learn to manage logically the code, you will be able to manage a complex project without become crazy

any advice we would give you would be generic software engineering dogma
like many classes/methods for tasks, but not too many
names that make sense
use comments (I guess hardly anyone does, because it would mean a lot of more work and would break the flow)

if you would post some something, people could give you specific advice

Try something new each time. Don’t worry if it doesn’t work. Just try again until it does, then select the best option and stick with that, and hopefully code size will shrink.

I already have packages and classes and I feel like it’s organized, but I still have to search through my classes to find certain methods and variables. For example, I’m in the process of drawing the equipment my player has equipped in the UI and it took me a few minutes to trace back through the player class and equipment class where I actually stored the equipment information. Also when I add more character classes(archer, wizard, etc) to my game, I’m going to have to go through quite a few java classes to add functionality for a new character class. I’m worried that it will be easy to miss places that I would need to add code for full functionality. Is this just inherent in bigger games?

I could upload my whole zip file project, but I feel it would be a lot to look through.

try to keep clear in your mind what are the pattern that u are using to solve your problem
and when u are adding new code and u see or you have the sensation that it is not the correct place,

stop and think because the answer are two:

a)the pattern that i have applied is incorrect or is not adapt to solve my problem (in this case iterate back to restructure your architecture/adapt the pattern to satisfy your requirements )
b)the place where i have put the code is wrong consider my pattern (move the code or rewrite in in accordance with your design )

try to be more specific in your question may be someone of us can give a detailetd answer
if u are not able try to make this exercie, take your code and try to designe your UML diagram (shore without detail)
u must be able to describe to yoursel your software and see what u don’t like

maybe you have actually way too many classes, which I often see in popular projects

but it seems that some people like it like that - I personally couldn’t find anything

To be honest, when I first started programming in Java, I had this problem too. I started programming in BASIC, and organizing code is a pain to do in BASIC because of the abstract loops. When I tried pushing what I knew from Basic to C++ and later Java, it became harder to find code and I found myself scared to look into my own code.

There is plenty that you can do to make your classes and code more readable. It all starts small.

1) Have a plan: It is very difficult to know how to write code if you don’t have a plan. I like to write down my ideas on a notebook, then I write little one-line comments inside my code that corresponds with the plan. It helps me to visualize a to do list and I can follow what classes match with the ideas I have.

2) Write meaningful variable names: These can be a lot more helpful than comments sometimes. I realized that if you have a variable name called character_HP instead of temp_variable_1. It’ll be easier to track where a variable is in relation to your code. Having great class names and function names goes a long way in organization.

3) Look at tutorials: If you didn’t take any programming classes (highly recommended btw). The next best thing you can do is look at how people in tutorials organize their code and base your code off of it. Java tutorials have extremely readable code filled with comments and information that is easy to follow. If you write code like they do, your code will naturally become more readable as well.

4) Write comments: It takes a few seconds to do, but in the long run it’ll make your code a lot easier for you to follow. You don’t even have to write JavaDocs, just basic one-liners put throughout your code will allow you to keep a log of what you were thinking. Very helpful when you come back after a year and forgot everything you did on that day.

Of course, organizing your code into separate folders, having good package names, indenting code, and using an IDE that has color coding really helps a lot. It is all about maintenance of your own code. If you don’t set strict guidelines for yourself on how to code, you code will become naturally messy and you’ll lose where things go. If you start out setting up rules for yourself early, your code will be a lot easier to read later on. It depends on you.

If I were you, I’d look into re-factoring the classes that have the most problems so you can continue coding. Once you find out what a variable does, write a comment in there so you don’t have to search twice.

It also help to know these ideas before cour code degrades. Code needs maintenance otherwise it goes bad like all unmaintained things :wink:

I never write comments or annotations, just annoys me when I move code around. Variable naming is far more important.

if you extract code blocks into methods, the method name will act as a comment already. (Extract method is a refactoring). There are ways to add information for the code reader without adding explicit comments.

This was my first contact with refactoring ideas, Opdykes Thesis:

http://c2.com/cgi/wiki?BillOpdyke

… mostly about smalltalk, but still valuable reading.

To some extend this is just normal. A bigger codebase has more interdependencies, and therefore there are more locations to check for side-effects. OOP was invented to help this, by keeping code and data which belong together, together (as an object or class). The idea of an interface (not only the Java syntax one) also was invented to make clear where responsibilities start and end, and how code parts communicate with each other.

Two basic rules:

  • Try to keep scopes local
  • Try to keep interfaces small

This helps to reduce the “range” and amount of possible side effects in your code, and help to add new features without needed to read too much old code.

If you really want to learn better programming, “Extreme Programming” might be of interest to you. Despite the name, it’s a very serious and well-thought approach to software development. Although there are others, and maybe better ones, it is really valuable for each developer to know about the ideas from XP:

http://www.extremeprogramming.org/

Good luck with improving your code :smiley:

I’m going to school to be a software engineer, but I’m just in my freshman year and I’m impatient and want to code now :slight_smile:

One thing that I haven’t understood from my classes is the idea of having variables private and using getters and setters. I feel like the code is much easier to use when variables are public, then I can use them anywhere without calling all sorts of get methods. This might help to encapsulate parts of my code, but the way my game runs right now, I need to access variables from many classes to keep it functional. Using getters and setters feels like the same thing as public variables except it’s harder to do what you want.

I’ll definitely try refactoring some of my code and hopefully it’ll get easier to use. One thing I have noticed that makes my code more complex is the use of HashMaps for quite a few things, like the storage of stats. I like them a lot, but now that I have a pretty large base on my game, I’m starting to lose track which keyword to use and where a hashmap is stored. This one is one that I really don’t like using because I always forget what I’ll get back:

//<equipmentName, <statName, stat>>
public HashMap<String, HashMap<String, Integer>> equipmentModifierStats = new HashMap<String, HashMap<String, Integer>>();

This is one of the few comments in my code because I always forget how this hashmap worked every time I need to use it.

[quote]try to keep clear in your mind what are the pattern that u are using to solve your problem
and when u are adding new code and u see or you have the sensation that it is not the correct place…
[/quote]
I do this every time I can’t find a variable I need to use, but when I find it, I remember why I put it there (it’ll only work in that spot, or makes more sense). Maybe I just need more practice in coding, because I’m trying to stick to a pattern, but I don’t remember it every time I need to find something.

Private/protected things (access modifiers) are for your organization, somewhat, but also for other people that don’t know your code as well as you do. If anything you make is used in a company or in a group they might not know that changing variable x will cause problems and therefore you will have to restrict it. Also, it follows OOP design, as some objects in your game probably shouldn’t know about some other objects, etc

I try to avoid string keys for exactly the reason you mention - it’s easy to forget what strings you are using for keys is it “armorType” or “armortype” and Java’s type system can’t really help you. I do this two ways:

  1. If possible, turn the hashmap into an object with a field name for each key. In your equipment example, if you had “sword” as a piece of equipment that had damage, toughness, weight, and material stats you could create a class called SwordEquipment that has damage, toughness, weight, and materialType fields. This way you can use the type system (and IDE autocompletion) to more easily identify what you can use.

  2. Another option is instead of strings, to use enums for keys. In your above example, you would have an enum that lists all of the equipment names and an enum for all of the statnames. Similarly to (1), this approach takes advantage of Java’s type system and if you misspell an equipment or stat name, you will get a compile time error.

In general, I think string keyed hashmaps are only really useful if the hashmap will have a lot of potential key values, that are not easy to specify in advance, and may change often. Otherwise, it is better to let the type system to do the work.

@actual
Completely agree with your points. Creating a class with 2 fields instead of a hashmap is much better for reusing and general design, so that the two fields do not have to be accessed through whichever class has the hashmap.
Enums will organize your code nicely because they kind of look like a class, while grouping all the “types” or “keys” together.

Hmmm… I’ll have to look up enums, I’ve never used them or seen them used. I don’t even know what they are :stuck_out_tongue: Hopefully that can make my code a little better. I’ve got a lot of work ahead of me trying to clean up my code because I’m not sure if I would be able to finish the game as it is. Thanks everyone for the tips!

If you ever want to get serious about programming and earn money with it, do yourself a favor and do not start with and get used to such bad habits.

The need to access everything from everywhere is a good sign of missing design, architecture, etc.
Better treat the cause (too much dependencies) instead of symptoms (publish all properties).

Right, so keep most variables private and only expose where it is necessary. Usually, only dumb data transport classes need getters and setters for all properties.

Get yourself a good book about software design, best practices, etc.

If you are working on a project, which you will sell, uplaod it to github. 8)

Public getters and setters expose data, so they aren’t there because of encapsulation.

But if you later needs to bind actions to such accesses, it much easier if you have a getter and setter already in place.

E.g. if you later find out that you need to trigger some game/display update upon a data change, it is much easier if you have a setter for that data, instead of a public writable data field.

For getters, an argument might be to have “access control” - you can pass an argument to the getter, and only if the getter code decides that the right “permit” was passed, it will return the actual value. Otherwise throw an IllegalAccessException. This way you can have a sort of security layer.