65

I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.

haylem
  • 28,856
  • 10
  • 103
  • 119
kullalok
  • 1,075
  • 3
  • 9
  • 10
  • 1
    To make each piece of the software more simple! http://www.infoq.com/presentations/Simple-Made-Easy-QCon-London-2012 – TehShrike Jun 26 '12 at 01:44
  • 51
    When you read your books, were they divided into chapters and sections? We split a program into classes to organize things, just like books divide text into chapters to organize things. – riwalk Jun 26 '12 at 05:02
  • 12
    The Romans used to say: divide et impera. – Giorgio Jun 26 '12 at 07:39
  • 8
    @Giorgio: or in English, because Latin is not so used any longer: **Divide And Conquer**. – Matthieu M. Jun 26 '12 at 13:41
  • 42
    Considering you're in grade 10, and have already been able to form an intelligent question, providing all the details necessary for good answers, providing context, and your relative experience, as well as background information into why you are asking the question; you are already more qualified than many people I currently work with... – CaffGeek Jun 26 '12 at 15:07
  • @Matthieu M: Thanks. Interestingly, the Latin word __imperare__ means __to rule__ rather than __to conquer__. However, the establish English version is divide and conquer. :-) – Giorgio Jun 26 '12 at 15:58
  • Hope you take the answers whole heartedly and later get a CS education. If you ended up writing code professionally like that you may encounter a homicidal programmer that had to maintain whatever you were paid to make down the road... – Rig Jun 27 '12 at 15:27
  • "although I have no idea what a Flash game is": a game made with Flash. This portal has only Flash games: http://www.kongregate.com/ – Martin Thoma Jul 02 '12 at 18:40
  • One reason I heard Robert C. Martin mention is independent deployability. This is more related to dependency inversion (the D in SOLID), but still is important when working on a big project. – Songo Sep 18 '14 at 09:53
  • I am so surprised that nobody mentioned the S in SOLID – Silviu Burcea Dec 12 '14 at 08:05
  • Here are three analogies: 1. Why separate the braking and propulsion systems in a car? Why not have the brakes applied to the pistons? 2. Instead of separating a school and a police station, why not combine them into a single building? Classrooms could go next to holding cells. 3. Why have a language built from indivisible letters and morphemes? We could describe things with long, unique sequences of syllables, e.g., instead of saying "President of the United States" (which is derived from Latin and Germanic morphemes), we will use this unique word: AstauandMizuxeSlabdrillZestybusFerirama. – emallove Jan 18 '17 at 18:42
  • related: [Why do we need so many classes in design patterns](https://softwareengineering.stackexchange.com/questions/369154/why-do-we-need-so-many-classes-in-design-patterns) – gnat Apr 10 '18 at 16:20

11 Answers11

73

The simplest answer is that if you put everything into one class, you have to worry about everything at once when you're writing new code. This may work for small projects, but for huge applications (we're talking hundreds of thousands of lines), this quickly becomes next to impossible.

To solve this issue, you break up pieces of functionality into their own classes and encapsulate all the logic. Then when you want to work on the class, you don't need to think about what else is going on in the code. You can just focus on that small piece of code. This is invaluable for working efficiently, however it's hard to appreciate without working on applications that are huge.

Of course there are countless other benefits to breaking your code into smaller pieces: the code is more maintainable, more testable, more reusable, etc., but to me the biggest benefit is that it makes massive programs manageable by reducing the amount of code you need to think about at one time.

Oleksi
  • 11,874
  • 2
  • 53
  • 54
  • 7
    A lot of concepts/ideas in programming (OO-principles, distributed source control, coding standards) only really make sense when you work on relatively large projects in a team. You'll understand why when you actually work on such projects. – joshin4colours Jun 26 '12 at 19:52
  • 40
    It's worth noting that *just* breaking the project up into multiple classes/files doesn't help much. What's really important is having **self-contained** classes, so changing one class doesn't require knowing anything else about the program (and using the class doesn't require any knowledge of how it was implemented). I bring this up because I frequently see code with a lot of classes, but no real encapsulation. Encapsulation is the important part -- how you achieve it is just details. – Brendan Long Jun 27 '12 at 21:19
  • 2
    Some key words would be "coupling" or "decoupling", "encapsulation", "information hiding". – marktani Jul 02 '12 at 20:09
  • @BrendanLong, I agree and I'll also add that encapsulation is almost impossible. Unless you're writing separate programs of course... BUT there are usually many parts that don't depend on each other, but only have shared dependencies – Jo So Jul 02 '18 at 10:22
29

Well, the simplest response might be "It helps organize things." If nothing else, you might compare it to sections in a notebook -- it's just plain simpler if you have "all the stuff relating to the UI" over here and "all the stuff relating to the gameplay" over there.

The more sophisticated answer is that divvying up work is not just convenient, but very important to managing complexity (and "managing complexity" is pretty much the name of the game when it comes to programming). Classes, or other types of module, allow you to "separate concerns." Not only do you know where to look for "stuff related to the UI" but you can be sure that if you want to make a change to the UI, you can just make it in the one place, and you don't have to worry "now, is that the only place where I set my font to Comic Sans?". And you can make a change and know that the effect of that change is only to whatever (small) scope is appropriate. If everything is in a single class or module, essentially everything is global, and that makes things very difficult to reason about.

In the specific case of classes as a type of software module, there's also a lot of behavior that is associated with a class, and most developers in the object-oriented paradigm find it very helpful to have meaningful names associated with the classes that group related functions together. So you probably wouldn't actually have a UI class, you'd probably have a Button class. There's a whole body of knowledge and techniques associated with object-oriented class design and it's the most common way of organizing large systems in mainstream programming.

Larry OBrien
  • 4,927
  • 2
  • 21
  • 25
12

This is a good question! Simple and well asked. Well... the answer is no so easy to understand for a student that is studying computer science and probably does not know in deep OO and probably does not have working on experience.

So, I can answer by describing a scenario and making you imagine how multi-classes software is better than monolithic software (made by one class only):

  • Readability: It is much harder to browse and write code inside a file with 10000 lines than several little and organized files.
  • Re-usability: If you write a single class, you can slip up in code duplication. This means more lines of code and probably more bugs(!)
  • Testability: What about testing a single functionality? If you isolate one logic functionality in one class, your life will be easier.
  • Code maintainability: You can fix a bug or enhance functionality with multiplie classes in one single place: The nice little classes.
  • Project structure: oooooh can you imagine how ugly a project with only one source file will appear?
Daenyth
  • 8,077
  • 3
  • 31
  • 46
Angelo Badellino
  • 704
  • 4
  • 13
  • I like your answer and I've just made some changes (that still need to get peer reviewed). A point I miss is easier detection of changes in Software versioning systems like SVN / GIT. It is also easier to work with multiple programmers in parallel for one project. – Martin Thoma Jul 02 '12 at 18:53
  • I would say separation of concerns, cohesion and decoupling is a concept that is on a way higher scope than the discipline of OOP. Imperative, logical and functional programmers alike all strive for high cohesion and low coupling. – sara May 04 '16 at 12:06
8

There are a lot of good answers here, and I definitely agree with them, but I feel that there's something more worth mentioning.

At the moment, as you've said, you're working solo on your project. However, in the future, there will be times when you will need to work in a team setting. During those times, you will be splitting the work (presumably the project will be fairly large). As a result there are a few (I guess really two major) different options. You can have multiple copies of one file, and work on separate "pieces" of the file and then "combine" them with copy and paste later and then modify so that your parts can work together, or you can split those "pieces" quite easily into different classes and discuss how you will be writing those classes, and use that knowledge to get going.

There will still need to be work to integrate all of the separate pieces together, but it will be a lot easier to maintain. Because x file contains y code and that's the code you know you need to modify. This goes into the organization thing that most of the other answers talk about.

Holding a program in one's head. Link from Giorgio

Sephallia
  • 181
  • 3
  • 1
    +1: Team work is also important! See e.g. http://www.paulgraham.com/head.html and the paragraph with the title "Don't have multiple people editing the same piece of code.". – Giorgio Jun 26 '12 at 21:21
  • @Giorgio I sort of only skimmed through it, but seems like an awesome resource! I'll add it to my answer simply because some people may not look in the comments section. Definitely going to give it a more thorough read some time. – Sephallia Jun 27 '12 at 14:34
  • This also applies to revision control -- working on separate files means less conflicts and merging. – Brendan Long Jun 27 '12 at 21:23
7

In effect what you have done is re-invented procedural programming. Mind you it is quite possible to write software that way and the compiler probably won't care. For many years this is how things were done until computers got faster and tools got better.

That being said if you break up your code into different logical units (Classes, modules etc) is that you can have a lot of short easy to understand pieces of code. that can be maintained later. Many of my modules are less than 20 lines of code. I know that all the code on a given subject is in a specific place. It also means that if someone else joins the project they will have a much easier time finding things.

As Gerald Sussman said our programs should be written first so that people can read it and second so that the computer can run it. (And if you have nto read "Structure and Interpretation of Computer Programs yet you should)

Zachary K
  • 10,433
  • 2
  • 37
  • 55
4

One uses multiple classes because as you get into bigger stuff you'll find there's simply no way you can keep track of everything when it's one big pile of code.

You simply have to divide and conquer to handle it.

Loren Pechtel
  • 3,371
  • 24
  • 19
3

Object oriented programming is the single best idea I've ever seen in programming. But it isn't the best thing in all cases, you need a bit of programming experience to see the point of it, and a lot of people are claiming to do OOP when they're not.

If you can look up "structured programming" you'll probably find something more immediately useful. (Make sure you read about old structured programming. Old terms often get new, fancier meanings, and you don't need anything fancy yet.) This is a rather simple concept about breaking your program down into subroutines, which is a lot easier than breaking it down into objects. The idea is your main program is a short routine that calls subroutines ("methods" in Java) to do the work. Each subroutine only knows what it's told by its parameters. (One of those parameters might be a file name, so you can cheat a bit.) So looking at the heading of a subroutine/method gives you a quick idea of what it does, and knowing what the methods in the main program do let you see what it does almost at a glance.

Then all the subroutines are broken down similarly till a few lines of code without any method calls will do the job. A main program that calls a few methods, each of which calls a few methods, each of which.... Down to small simple methods that do the work. In this way, you can look at any part of a very large program (or small program) and quickly understand what it does.

Java is very specifically designed for people who are writing Object Oriented code. But even the most intense OO program uses some structured programming, and you can always subvert any language. (I did OO in plain C.) So you can do SP, or anything else, in Java. Forget classes and focus on big methods that can be broken down into small, managable ones. I should add that SP helps a lot with letting you reuse your code, and also with the DRY (google it, but it means "Don't Repeat Yourself") principle.

Hopefully I've explained why and how to split up your code into multiple parts without bringing in "classes". They're a great idea and are just the thing for games and Java's a great language for OOP. But it's better to know why you're doing what you're doing. Leave OOP alone until it starts to make some sense to you.

RalphChapin
  • 3,270
  • 1
  • 14
  • 16
0

One of the benefits is re-usability. A program is basically a bunch instructions grouped together. You'd find that some of those instructions are suitable for other programs as well.

Let's say you make a jumping game. Later on when you decide to make a cannon game, you find that the physics calculation you used in the jumping game comes handy here.

So instead of writing it again, or worse copy and pasting it into the new program, you make it into a class. So next time you make another game where the game mechanics requires physics, you could just reuse it. Of course this is oversimplified but I hope it makes sense.

0

First of all, note that I'm a C++ and Python, not Java, so some of this may not apply quite as fully. Please correct me if I make some incorrect assumptions about how classes work in Java.

Classes are primarily useful when they are instantiated. A class of which no instances are created really is really just a glorified namespace. If you use all your classes this way, then indeed, the benefits of moving things from namespace to namespace may seem insignificant -- at most, you'll win by having some private data in each and thereby encapsulate things a little.

However, this isn't where classes shine. Consider the String class: you could have all the same features using char arrays and some static functions. At this point, functions give you a little extra safety and syntactic sugar. You can write string.length() instead of length(char_array); that's not a very big deal, but many people still like it. Moreover, you know that if someone gave you a String, it was created with the String constructor and that it must work with the length function -- if the array version can't handle some character then it has no way of preventing you from putting it in there.

That's still not it, though. The key point is that classes bundle data and functions that operate on it and abstract both of it away. When you have a method void f(Builder b) you know you'll be getting a Builder, and you can expect that it will support certain behaviour. However, you know nothing of data or the functions being executed -- in fact, the definitions for both may not be written yet as you write and compile f.

The first point to understand is thus that classes make it convenient to pass around data while making sure it is not broken. The second point is that both what data and what function (implementations) an object has is something about the object, not something you can just tell from its type.

Cactus Golov
  • 875
  • 7
  • 13
0

The whole idea is based on a general rule named divide and conquer .
This paradigm can be used almost every where; you divide a problem into smaller problems and then you solve these little, simple and well-known problems .
Dividing your program into classes is one of the types of division which started to become common in last decade . In this programming paradigm we model our problem by some objects and try to solve the problem by sending messages between these objects .
Some people might say that this approach is easier to comprehend, expand and debug .
Although some people disagree :)

Rsh
  • 101
  • 2
0

It is not about splitting a program into classes but about how you model your application i.e. how you visualize parts of your application. Splitting things is just a mechanism we use to understand complex things better. It is not only with programming. Imagine circuit board with many wires entangled with each other, forming a complex structure with each wire connecting somewhere (spaghetti code). You'll have to follow each wire to its end to figure out the connections. On the contrary imagine wires that are grouped and color coded as per their function. It becomes a lot easier to fix things.

Idea is that you don't start with a long program and then split it into classes. But you model your application in terms of objects/classes first and then connect them to build applications.

Vamsi
  • 111
  • 2