52

Instantiating a new object is always better, then you have 1 place to initialise the properties (the constructor) and can easily update it. Imagine you add a new property to the class, you would rather update the constructor than add a new method that also re-initialises all properties. Now, there are cases where you might want to re-use an object, one ...


50

Code Complete (and many other software engineering resources) emphasizes matching your classes to real world objects. I believe the fundamental reason for this is that it makes it more likely that you have a true grasp of what it is that you're implementing, rather than hacking away at an intangible idea. If you're a subscriber to this theory, I don't see ...


44

A Start() method (like Run(), Execute() or anything similar) is appropriate when the cost of constructing the object is low, but the cost of using it is high. For example: A class which encapsulates a best-path-optimization algorithm. It's trivial to set it up with a set of parameters (X squares by Y squares, with suchandsuch evaluation method), but it may ...


17

You should definitely prefer creating a new object in the vast majority of cases. Problems with reassigning all properties: Requires public setters on all properties, which drastically limits the level of encapsulation you can provide Knowing whether you have any additional use for the old instance means you need to know everywhere that the old instance is ...


14

You may use lazy initialization. In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. That way you avoid temporal-coupling, meaning the consumer of your class has to call certain methods in certain order. Having ...


10

Given the very generic example, it's hard to tell. If "resetting the properties" makes semantic sense in the case of the domain, it will make more sense to the consumer of your class to call MyObject.Reset(); // Sets all necessary properties to null Than MyObject = new MyClass(); I would NEVER require making the consumer of your class call MyObject....


9

The object initialization sequence is complex enough as it is and already sometimes causes headaches. Allowing subclasses to run code before the superclass constructor would make it more complex and confusing still, with more potential for subtle bugs, especially if there is a hierarchy of multiple classes which all do this. It also reduces the conceptual ...


5

As Harrison Paine and Brandin suggest, I would re-use the same object and factorize the initialization of the properties in a Reset method: public class MyClass { public MyClass() { this.Reset() } public void Reset() { this.Prop1 = whatever this.Prop2 = you name it this.Prop3 = oh yeah } public object Prop1 { get; ...


4

Based on what you describe, then, yes, it is a necessary evil to call the open method even though, as you say, a failure of open will inappropriately show failures of all the dependent tests. However, I would recommend a rather different approach. Any classes that have to go to "bare metal" (i.e. touch system resources) should strive to be conduit-only ...


4

dedicated Initialise method is bad - if you use this you must construct an object and then not use it at all until you've successfully called Init, and always destroy it if the Init call fails. Its a mess of initialisation that is much better handled in the constructor. If you only return a successfully constructed object that contains everything it needs ...


4

When you inherit from an object, you may not be able to see the implementation of the constructor or underlying methods. There may be more going on in the constructor than just initialization of variables. such as hardware access, database access, network communication, etc. Not saying this is good design or not - just saying you may not be aware of it. ...


3

I thinks this statement is true only if admit that constructed != initialized. You are missing the point it seems. Calling virtual methods from the constructor implicitly means that the object is not yet fully constructed (and initialized). The concepts are the same. You can't call virtual methods until all of the constructors have run (the object is fully ...


3

So: How is it that I can reference an object while it is still being constructed? Presumably Because it's useful (though in a dangerous way) for exactly the scenario you describe, so the language designers decided to allow it. Technically, it's not a problem at all: while the object is being constructed, its memory must already be allocated, so you can ...


3

You first create a cucumber and, by duck is a duck principle, it becomes a vegetable. Except Java isn't a structurally (duck) typed language. It's a nominatively typed language. If Java was a structurally typed language (or simply a dynamic one), then your mental picture of how it works would be good. Since it is not, it needs to build the object layout ...


3

Generally, what is the preferred method for the problem described above, or which method is preferred in which cases? The prefered method looks like this: class Object { ... }; std::istream& operator>>(std::istream& in, Object& obj) { /* classic "in" operator*/ } Client code (1): Object o; if(std::cin >> o) { // do something ...


3

Don't confuse "exception" with "rare" The main point of exceptions and exception handling is keeping different types of code apart: The code that provides the main functionality (the "happy path" code) Everything else: The code that handles all those 973 other cases where not everything has worked out wonderfully and precisely to your main functionality's ...


3

Here's the thing with unit tests. You want them to be really easy to write. Anytime writing a test is made more difficult, it will result in tests not being written, and bugs will be allowed to live. So let's imagine I'm writing a test: void testCanDrive() { Person person = new PersonBuilder() .doRequired() .addFirstName("John") ....


3

I'll start by pointing out that building complex objects in a constructor is not always a good idea. That said, if it's the way your code currently behaves, and you don't want to change that, you should probably be able to trade your constructors for lightweight factories. Instead of A() doing new C() and then deciding it didn't really need it, you could ...


2

I would do this by using a Map<Id, Container> at each level of the data structure. Write a private helper method that will return the container if it already exists, or creates a new Container if it does not yet exist. This is method is commonly called getOrAdd. As usual, making sure that the the underlying container still exists is a bunch of ...


2

I think most people answering to favoring creating a new object are missing a critical scenario: garbage collection (GC). GC can have a real performance hit in applications that creating a lot of objects (think games, or scientific applications). Let's say I have an expression tree that represents a mathematical expression, where in the inner nodes are ...


2

If the intended usage pattern for a class is that a single owner will keep a reference to each instance, no other code will keep copies of the references, and it will be very common for owners to have loops which need to, many times, "fill in" a blank instance, use it temporarily, and never need it again (a common class meeting such a criterion would be ...


1

The alternatives depend on the general structure of your parser (and lexer) and what the consequences and costs are if you guess wrong about dealing with a foo or a foo_special object. As a first alternative, you can drop the inheritance of foo_special and foo nd instead model their relation more along the structure of your grammar: foo_special contains a ...


1

It doesn't work like that. Most of the work is done directly or indirectly in your view controllers. You don't create view controllers when the app is launched, but when they are needed. And the real work is done in viewDidLoad. And viewControllers get destroyed when not needed anymore. Lots of work is done in Singletons, and they are created when they are ...


1

Take a look at this iOS lifecycle. I have never read Clean Code, but I would suggest sticking to an MVC /MVVM pattern for iOS. iOS should do most of the heavy startup/construction process that I believe Robert is referring to. Your business logic will go into your respective controllers (note I did not read that link I just grabbed the first google hit) ...


1

Your underlying problem is that 0 is an incorrect value for the id's Ideally you would change them to GUIDs but a second best would be to change them to nullable uints. This would allow you to have them set to null untill the object had been persisted and got actual ids


1

Why this happens is because this is a reference to the memory area that your object is currently occupying. Since instructions in the code are executed sequentially, you already have your object in some state that's being referenced when you get to the point of calling the key() method. Although this is possible, the entire approach is wrong. The methods ...


1

o, let's say I have an some DataAccessLayer which wraps my DataAccessDriver. I doubt very much there should be such a strong dependency. I vote for serialization subsystem to be completely independent from other things in your application. Note: I vote for serialization to be independent from persistence layer. Serializing an object is one responsibility, ...


1

In layman's words: An inheritance relationship is an "IS A" relationship. If Human inherits from Ape, it means that a Human is, firstly, an Ape then a Human. ( I'm not saying humans descent from apes, but that they are apes ). It makes sense that you first initialize your Ape self in order to built upon it and get to be your Human self. The superclass is ...


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