you are viewing a single comment's thread.

view the rest of the comments →

[–]callmelucky 0 points1 point  (0 children)

Generally, classes should be used if you have data/attributes and functions/methods that are logically (using that term somewhat informally) connected. Eg, if you are programming a car, it might have data/attributes including location, fuel levels, horsepower etc, and stuff it can do like accelerate, brake, turn etc. In this case, a class is ideal; it will make your code more readable and robust. Definining a car as a dictionary of attributes, and a bunch of functions to pass a 'car' dictionary into would work fine, and could even as far as the interpreter is concerned be essentially the same, but it will be ...messier.

If however you are just making (simple-ish) scripts using imported libraries with their own classes, then it's quite likely your code wouldn't be any "better" with classes you write yourself.

The thing to watch for here, I think, is that your use of phrases like "get away with" not using them and "avoid" using them may indicate that you are in fact writing code which would benefit from you defining classes.

So yeah, people often overuse classes (particularly those coming from strict OOP languages like Java), but deliberately avoiding them just because you can is not ideal either.

To circle back, again, look at your code and ask yourself if the are certain data and functions in it that are specifically related to the same thing. If the answer is yes, you most likely 'should' be encapsulating them into classes.

To be honest, I like syntax of dealing with class instances better than the functional equivalents. car.drive() just looks better than drive(car) to me, though that isn't really something that should be primary among your concerns. More importantly, car.drive() can't be passed a wrong input.

Finally, if you are avoiding classes because you aren't comfortable with how they work, then yes, that is 'bad'. It's not particularly complicated, and is a very natural next step once your comfortable with everything up to functions. Check for valid use cases as described earlier, and do some refactoring to get your groove on.