Tag Info

New answers tagged

1

TL;DR: Different subtype constructors are not only ok, they are expected. Liskov directly addresses the usage of different constructors in her paper Behavioral Subtyping Using Invariants and Constraints which is the formalization of the principle. "..omitting creators [from the type specification] makes it easy for a type to have multiple implementations, ...


4

Consider a repository of citation information. containing books, articles, journals, edited books, and conference papers. Your task is to format the contents of the repository for consumption. Let's take two approaches to formatting. National Library of Medicine (derived from the Vancouver Project) specifies citations in a particular way, mostly affecting ...


1

The answer is of course "it depends," but given your use case, I would say no. Here's why: C# is a wonderful - scratch that, the best - object-oriented language around. It is so good, in fact, that I will sometimes get caught up trying to implement a fanatically purist vision of what began as a simple project. That doesn't happen to me so much when writing ...


0

In my view custom exceptions make sense only in 2 cases: 1) you're developing an Api 2) you use it in your code to recover from a failure. In any other scenario, built in exceptions should be sufficient. In your case you could use InvalidArgumentException


3

In general Subclassing exceptions is a good idea to group the exceptions into the families or groupings that they belong to. It also allows client code the opportunity to handle exceptions based on specific errors or more generally. I usually divide the tree somewhere near the root between the logical and runtime errors (e.g. in C++ the std::runtime_error ...


0

Encapsulation and Data Abstraction are related, yet different concepts. Encapsulation is about designing a class. Data abstraction is about designing an algorithm. An easy explanation would be: Encapsulation asks the question: What are the legal ways of interacting with this implementation? Data Abstraction asks the question: What is the set of ...


1

tl;dr Your decisions on how much to abstract should be dependent upon your business problem to choose how much of the baby to split. Understanding relationships and how to define them properly without creating 'god' objects is a common problem when architecting solutions. Your idea on compromise is spot on when you are trying to accomplish something and ...


0

I think we've learned a lot since SRP was introduced, but in a more indirect and general way due to the changes in the way software development projects are managed. SRP is a principle that wasn't intended to have a set of strict rules that could be blindly applied to all situations. It depends. There are some general rules that experience has taught us that ...


0

I learnt from my teacher that, Data abstraction is the methodology to enforce barrier between representation and interface. No, abstraction is not just having public and private methods in a class. Abstraction is having just an interface and implementing one or more classes against this interface. An example: public void printAll(List<String> ...


2

Another approach would be to use composition instead of inheritance. We can look to the command pattern for inspiration. We would like to have a common interface while allowing variable actions. Rather than write the behavior into the Item itself (as durron597 does), we could instead create an intermediary object to hold the interactive behavior we want. ...


0

While instanceof should be avoided some Java interfaces require it as part of their contract. For example: javax.security.auth.callback.CallbackHandler. It defines: void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException Callback is an interface with no methods so the only way to differentiate different types of Callback ...


0

I don't fully understand your requirements, but to me it seems you hit a point where C#'s type system is more going to get in the way than actually help you. I would simply drop the idea of using classes and inheritance and just create a generic key-value store where key it name or type of the propery and value is an object containing the value of the ...


1

Using strategy objects in the described way is a good start to simplify your PointBase class, I would not hesitate to introduce them even if they do not solve your problem with the BreakEven property. For allowing custom properties, you could provide some kind "extension mechanism" in your PointBase class (which I would rename to Point after the redesign). ...


2

I posted a question here that was brought about by the same problem: trying to both take advantage of the convenience of referring to objects by their base class, while at the same time using additional properties that their subclasses may contain. The solution that was most useful to me was to use the visitor pattern. In your Point base class, you define ...


0

I'd suggest you come at the ISP from the perspective of client code. In how many places is your class being used? Is there any client class that only needs one method but not the other? If all client code needs both, there really doesn't seem to be a case for two interfaces. If you do have two different places where your class is being used, with each ...


-3

One concrete example is when you update a class. A new class object is created and then it is swapped with the previous one. This is done because all objects of that class already know their class, and as you have to replace it at one time for all of them, become makes a good sense.


9

Gilad Bracha talks about become: at some length: One of Smalltalk’s most unique and powerful features is also one of the least known outside the Smalltalk community. It’s a little method called become: . What become: does is swap the identities of its receiver and its argument. That is, after a become: b all references to the object ...


1

Composite often goes hand in hand with Builder pattern to address exactly the problem you have mentioned here. You can create a separate class, call it PageBuilder (or whatever suits your fancy) and move all the building logic into that class. Although I don't know the internals of your code but considering a very generic composite/builder duo here is some ...


1

Interfaces are a static tool that allows programmers to guarantee what methods an object supports. You are trying to use them as a dynamic mechanism for allowing users - or, more precisely, the user interface - to infer the actions users are allowed to do on the the object. What you need is a uniform way to programmatically access the list of actions at ...


0

If class Foo accepts references to objects of its type from outside code and uses private members thereof, then outside code will need to use references of type Foo or one of its subtypes. If Foo didn't need to use private members of its own type, but it implemented an interface which included all the members it did need to use, then it would be possible ...


6

I think you are suffering from YAGNI in your design. Think about it like this - when would you ever interact with a clock and a seat in the same way? Answer: you wouldn't! You might name a clock, and name a seat, but you wouldn't sit on a clock, nor would you increment a seat. It doesn't make any sense. Interfaces are for common behavior. For example, you ...


0

A static class with only static methods and static data is nothing more or less then a collection of global variables and a library of functions disguised as something resembling OO. Such a class need never be instantiated because the result will not be an object, just an empty shell.


7

If I understand you correctly, it sounds like you're working with something like this pseudocode: void foo(Item i) { if(i instanceof Clock) { (i as Clock).increment(); } else if(i instanceof Chair) { (i as Chair).sit(); } } As you suspect, this is a code smell. A pretty strong one, actually. The immediate problem is that, because ...


3

That's exactly what interfaces are for. The programmer doesn't care what types of objects might be in the list, as long as they provide the method calls expected of any Observer. This way, your list can contain instances of MyTopicSubscriber, MyFileSystemChangeSubscriber, MyMailboxSubscriber, etc. (these are fictitious titles, of course). By using ...


1

Yes, you are missing OOP principles in your coding. OOP is not about bearing primitive types, OOP is about having an object that has responsibilities(methods essentially). GRASP Principles are a good start to learn where which method belongs in OOP. In OOP you want to treat most instances as objects that have responsibilities and instance fields(instance ...


1

You can make it all static, but that will result in (arguably) unnecessary stronger coupling & dependency between the clients of the manager and the manager. Thus, I agree with @DavidArno on avoiding static state as much as possible. As @RobertHarvey noted, for logging, I use a static variable to hold a reference to a logger object because ...


5

I would argue that no class should ever have static data. That lies the road to testing hell and non-threadsafe code. Also: Only make methods static if they have zero side-effects (ie only process the data passed as parameters in a deterministic fashion). Do not couple classes, such as having setMixedState rely on accessing Node, pass the method what it ...


3

To answer this, we should clarify the definition of static: Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to static variables in that sense. An example would be a static method to sum the values of all the variables of an instance for a class. For example, if there were a ...


4

The widespread antipathy towards static methods is largely due to fear that you won't be able to override a method easily for testing the class or mocking to test another class. With a private method this isn't a concern, so my opinion is: if it can be static, make it static - this acts as a useful bit of automatic documentation ("this method does not ...


5

Two solutions. Simple: Don't include setters as noted by David for immutable readonly objects. Alternatively: Allow setters to return a new immutable object, verbose in comparison to the former but provides state over time for each initialised object. This design is a very useful tool for Thread safety and immutability which extends over all imperative ...


41

With C#5 and before, we were faced with two options for immutable fields exposed via a getter: Create a read-only backing variable and return that via a manual getter. This option is secure (one must explicitly remove the readonly to destroy the immutability. It created lots of boiler-plate code though. Use an auto-property, with a private setter. This ...


11

You could just get rid of the setters. They don't do anything, they will confuse users and they will lead to bugs. However, you could instead make them private and thus get rid of the backing variables, simplifying your code: public class Thing { public Thing(int foo, int bar) { Foo = foo; Bar = bar; } public int Foo { get; ...


101

Why make that code legal? Take out the set { } if it does nothing. This is how you define a read only public property: public int Foo { get { return _foo; } }


1

You can't make a Java program without objects. Everything you instantiate is an object. The static methods you call are called on instances of the Class object of their class. But yes, it's generally a bad idea to use a single big class with just static methods. It gets terribly unwieldy really quickly. Rather than avoid the issue of learning object ...


3

For this particular problem, it's not terrible. What you're doing is basically scripting an import process, which is a fairly straight-forward imperative problem. Java maybe isn't the best tool for that job, but it's fine. An experienced programmer might create an intermediary data structure to represent the data going into the database to help should that ...


3

The point of object-orientation is not to count the user-defined classes and judge via "more == better". Instantiating an object is useful if you really do have multiple things in your problem field that have identical behaviour but a distinct identity. You saw how that works with streams: one reads from one source, the next one from another; reading and ...


3

At a high level, you're essentially asking: Is building a Controller cache better than using singletons? I would argue that in your situation, yes, it is. And here's why. From your description it doesn't sound like you need the semantics of a singleton here. Your game would be just fine if you instantiated a new Controller every time one was needed. In ...


1

It should be absolutely fine. You simply are not assigning the object to any variable and gets disposed of automatically. BUT, I would look at larger scope issues here: If you don't need an object, class(or method I guess in PHP) should be static instead. // Static invocation myClass::myMethod();


2

Given that the removal is handled in generally the same way, there is really nothing wrong with this approach of having a default handling in the parent class and overridden implementations where required. Adding other intermediary objects does not solve the fact that you have some common operations that are applicable across a range of classes. If you are ...


-2

Why not do something like this class Animals { /***/ } class HeavyAnimals{} : Animals //The basic class for animals like the African Bison With the class HeavyAnimals you can create the African Bison class by extending the HeavyAnimals class. So now you the parent class (the Animals) which can be use to create other base class like the HeavyAnimal ...


0

I have encountered this issue several times and found the following solution at best. Please keep in mind this is my approach and your preference may be different. I always try to keep any form of SQL interaction inside the repository. Therefore the create method should be declared inside the repository. Now the issue with the ID persists. When looking at ...


2

$this->$data['id'] = $db->insertANewProduct($data); I think is a bad practice, because breaks de Single Responsibility Principle, the product class knows it's been persisted. You are loosing what you win with the repository pattern. If you want to do that another option (less OO) is Active Record. I would choose the option 1 public function ...


3

Firstly, is this a correct approach or is it better to keep the array? Also, does an interface / base class need functions defined? Or can these be defined later? Yes, an interface need functions defined, if not where is the sense of having an interface? An interface works like a contract between a consumer and his client. In this case the Main ...


3

Consider these points: The "S" in solid does not mean "do one thing." It means "have one responsibility." If you find that your classes are proliferating, they may be too small. There's nothing wrong with a class doing many things, so long as those things all pertain to a single responsibility. Consider the case of a repository, which has several ...


2

Private getters and setters wouldn't even make that much sense, really. You would be encapsulating the encapsulation and bloat your class, making it hard to read. The reason people create getters and setters is to restrict the client from doing something stupid with the class data, and for hiding what the class does to the data from the client.


1

As opposite examples, in Objective-C or Swift you won't see any setThing anymore, and there never was a getThing. In modern use, you have properties in Objective-C and variables in Swift, which are used exactly as if they were plain old member variables that you can read and write. What's going on behind the scenes is then something entirely different. Your ...


1

Naming conventions are simply suggestions. There are no set rules for anything. The only guideline you need to follow is to name your function according to what it does. If your function readFileContents both reads and returns parts of the file, consider splitting it up into two functions, readFileContents and getFileContents, for example. readFileContents ...


2

The OOP way is to combine together polymorphism and recursion. A binary tree is defined as either empty or a set of value, left and right where both left and right are binary trees. To represent it properly left and right must be binary tree themselves, even if they are empty. To represent that in object oriented way, we'll have a tree base class and node ...


0

I see you use php, try to stick to the psr coding styles: psr-1 and psr-2. Look into the decorator pattern. this is a pattern commonly used in these kind of situations. Edit: added a small example You probably have some kind of LineItem class that is used to represent items in your cart. They probably look something like this: interface LineItem { ...


3

For the most part, VBA uses late binding, not the kind of early binding that you are describing. In strongly-typed languages like C#, you will get the behavior you expect, because the compiler will check your method calls against the class definitions and complain that they don't match. This is early-binding. But in a loosely-typed, late-binding language ...



Top 50 recent answers are included