Hot answers tagged

110

No, an object does not have to represent an entity. In fact, I would argue that when you stop thinking about objects as physical entities is when you finally get the benefits that OOP promises. This isn't the best example, but the Coffee Maker design is probably where the light started to come on for me. Objects are about messages. They're about ...


82

The characteristic of being static is independent of the visibility. The reasons that you will want to have a static method (some code that does not depend on non-static members) will still be useful. But maybe you don't want anyone/anything else to use it, just your class.


54

In Item 5, of Effective Java, Joshua Bloch says The lesson is clear: prefer primitives to boxed primitives, and watch out for unintentional autoboxing. One good use for classes is when using them as generic types (including Collection classes, such as lists and maps) or when you want to transform them to other type without implicit casting (for example ...


46

It depends on what you mean by "required". Access modifiers are not a necessity. You could replace every access modifier with public and most applications will work just like they did when you used varied access modifiers, proving the point that the compiler's main goal (outputting a working application) is not directly dependent on access modifiers. As ...


45

It's not totally clear what your question is, but if the values are truly constant, I don't see a problem with the simple option of: public static class LocationConstants { public const string StateId = "ST"; public const string CountryId = "CI"; } Using static in the class declaration signals your intention for the purpose of ...


42

A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance. I've done similar things ...


41

A constructor with arguments isn't just a handy shorthand for using setters. You write a constructor in order to ensure that an object will never, ever exist without certain data being present. If there is no such requirement, fine. But if there is one, as indicated by the fact that you've written such a constructor, then it would be irresponsible to ...


39

They both are member variables, meaning that both are associated with a class. Now of course, there are differences between the two: Instance variables: These variables belong to the instance of a class, thus an object. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances ...


36

No, it's not required: Bjarne Stroustrup, explained how he naively added protected to C++ release 1.2, thinking to provide a useful feature to class developers, just to conclude only 5 years later that it was a nasty source of bugs, that fortunately no one was forced to use. Nowadays, he recommends not to use it. The practical arguments against ...


35

If the class has no state, you could consider turning it into a function or static method depending on your language.


33

The answer implied by the concept of classes is "no". Either whatever action, data or relation you're handling is part of all subclasses - then it should be handled in the superclass without checking the actual type. Or it applies only to some subclasses - then you'd have to perform run-time type checks to do the right thing, the superclass would have to ...


32

The standard practice is to go with the primitives, unless you're dealing with generics (make sure you are aware of autoboxing & unboxing!). There are a number of good reasons to follow the convention: 1. You avoid simple mistakes: There are some subtle, non-intuitive cases which often catch out beginners. Even experienced coders slip up and make ...


31

A fairly common reason (in Java) would be for initializing immutable field variables in a constructor by using a simple private static method to reduce constructor clutter. It is private: external classes should not see it. It is static: it can perform some operation, independent1 of the state of the host class. A somewhat contrived example follows... eg: ...


30

Joshua Bloch in Item 22 of his book "Effective Java Second Edition" tells when to use which kind of nested class and why. There are some quotes below: One common use of a static member class is as a public helper class, useful only in conjunction with its outer class. For example, consider an enum describing the operations supported by a calculator. The ...


30

Neither. I take it you're asking whether having the same set of field types is enough to classify as being the same class, or whether they have to be named identically as well. The answer is: "Not even having the same types and the same names is sufficient!" Structurally equivalent classes are not necessarily type-compatible. For instance, if you have a ...


27

An alternative to friend (well, in a sense) that I use frequently is a pattern that I've come to know as access_by. It's pretty simple: class A { void priv_method(){}; public: template <class T> struct access_by; template <class T> friend struct access_by; } Now, suppose class B is involved in testing A. You can write this: template <...


25

Why use a class? Because it makes the job easier, assuming you know how to do object oriented programming, and assuming you're writing a non-trivial GUI. Using objects allows you to easily divide your code into modular units that are self contained, and modularizing your code is generally considered to be a best practice. GUI programming readily lends ...


23

It is sometimes considered that the singleton is an anti-pattern. Unless the problem being solved specifically requires the use of the singleton pattern, it is generally best to avoid it. You mention that the function would have no state or other long lived requirements, so the immediate need for an object is not there either. A free function would be best ...


21

A common use-case for a private static method is a utility method which is only used by that one class is independent of the internal state of that class


21

Can classes represent entity-less objects? If not, why they are bad/incomplete/non-OOP-centric? Are there ways they need to be changed/improved? In short, you can do anything, but this specific scenario would be against OOP principles :) What you are describing is sometimes called a "utility" class - usually a sign of code smell. You want to avoid creating ...


19

You see that you have a few lines of code that is repeated in a lot of your methods, so you decide to extract them to a single method, as duplicated code is not good. You make the method private as it is not designed for widespread usage and you don’t want unrelated code calling it. (Debate this point in the comments….) As the method does not access any ...


18

True private methods - those that can't be seen or used from outside of a class - do not exist in Python. What we have are conventions that are merely suggestions to not touch things you shouldn't. The closest you get to privacy is name mangling. An attribute of MyClass named __some_attr will just be renamed to _MyClass__some_attr internally, making it ...


18

A python module is nothing but a package to encapsulate reusable code. Modules usually, but not always, reside in a folder with a __init__.py file inside of it. Modules can contain functions but also classes. Modules are imported using the import keyword. Python has a way to put definitions in a file and use them in a script or in an interactive ...


18

There are two parts in your question. The first part is the organization of C++ header files and source files. This is solved by using forward declaration and the separation of the class declaration (putting them in the header file) and method body (putting them in the source file). Furthermore, in some cases one can apply the Pimpl idiom ("pointer to ...


18

When a function is defined as part of the class definition, it is implicitly inline (regardless of whether you use that keyword). This has a number of consequences. The function may be inlined by the compiler, potentially but not necessarily resulting in a faster program. Thus, different compilation units can get different copies of this function. The One ...


16

Not only should it not know, it simply can't! Usually, a class can be extended anytime, anywhere. It can be extended by classes that didn't even exist when it was written. Some languages allow extending classes to be controlled by the superclass. In Scala, a class can be marked as sealed, which means that it can only by extended by other classes within the ...


15

lol you sound like a team that I used to work on ;) Java (and probably C#) certainly supports that programming style. And I work with people who's first instinct is, "I can make that a static method!" But there are some subtle costs that catch up with you over time. 1) Java is an Object Oriented language. And it drives the functional guys nuts, but really ...


15

Can classes represent entity-less objects? Can? Yes. Should? Probably not - or at least, not how you're phrasing things. Objects actually are best when not representing a physical object directly since reality so infrequently maps nicely to code. But they do need to represent a cohesive concept or code-object. They need to represent a single cohesive ...


14

How many dimensions are needed? C++ Template programming may require some code duplication for each level of higher dimension. Address calculation is the easy part. A simple approach can be used for dimensions up to a dozen. For a 3-dimensional example: Let the size of the array be [m, n, p] For each dimension, we calculate a "weight vector" by ...


14

Avoid the Gang of Four Singleton pattern, for reasons cited in the other answers. Mainly it is an anti-pattern based on difficulties it creates for testing. Factory and Dependency Injection made Singleton obsolete. The best answer is to use a Factory that decides whether to instantiate one instance, or many, of a given class. That way, the class and its ...


Only top voted, non community-wiki answers of a minimum length are eligible