Tag Info

New answers tagged

0

You may want to use a BitmapLoader which lazily loads the Bitmaps as and when required. This way you don't have to maintain any internal members. If required you can implement some sort of LRU caching in the BitmapLoader to optimise the loading of the most frequently accesses Bitmaps.


0

I am not sure about Java, but C# has a whole set of framework design guidelines, that includes naming conventions for public and protected members. Protected fields are not recommended. Use protected properties instead.


0

It is perfectly fine for a child object to have a reference to its parent. There is no unnecessary recursion and no sloppiness. Naturally, that would be a construction-time parameter, and it would be stored in a readonly member, so there would be no set. Then, the table could obtain the connection string from the database object, if it really needed to. ...


5

Pass an already established connection to Table's constructor (as opossed to the other answer suggestion of passing the connection string). That's the approach I've used for years. Objects that access the database don't open or close database connections. A connection is made by some other component, usually the main class, and passed to the constructors of ...


0

Pass a reference to the ConnectionString (or better yet, the actual Connection) to the Table's constructor. Since the Table is already inside the Database (and doesn't really belong anywhere else), the Database can simply give it the magic string during construction, and then the Table always has what it needs to execute the row count logic. Since your ...


3

I believe that you should either expose object TextBlock from Page or have delegate methods in Page to provide access to the methods of TextBlock but not both. I guess it depends how many properties and methods of TextBlock you want to expose, so if they are many, that just provide TextBlock and do not have all those simple delegations. You can also check ...


1

I think you're looking for 2 things, but I answered this question a while ago This is a very clear example of the Command Pattern Basically it goes like this: Look up the thing to do Do it If you use a defaulting map (there are implementations around) then, in the event the command was not found, you can do the default which can use the Null Object ...


2

Making "wrapper properties" like this is fine if it's the cleanest way to implement the API that you want this class to have. However, the specific example you posted does look questionable to me, mostly because the user of your class can now do exactly the same thing in two different ways: myPage.MainParagraph.Text and myPage.MainText. Since the user ...


2

Your class is called RVDBuilder. The point of the builder pattern is to avoid ridiculously complex constructors and instead allow you to gradually collect all necessary information via ordinary method calls. Therefore, the best solution would be to add a fluent interface to add pairs of information: class RVDBuilder { public RVDBuilder Add(string key, ...


2

It depends, is the state you're locking private or protected? If it's protected, I recommend you reconsider. Once you've reconsidered, make the lock object as public as the most public shared state. If you trust derived types to use the state properly, then you should trust them to handle the locking properly. If you don't provide the lock, they'll be ...


4

I had to tackle this recently in Java. My solution was to make the Pair class fairly painless to instantiate: Pair.of(..., ...). That's only 7 extra characters before the parentheses, and naming the factory method of seems to be a convention that value-based classes follow in Java 8. But in my use case there were usually no more than 3-4 pairs, so I also ...


3

I read in "Effective C++" that APIs should always be easy to use correctly and hard to use incorrectly. Since you've stated that it can be used incorrectly, I would ditch it for a solution that can be safer.


2

The strictest Object Oriented definition of a subclass relationship is known as «is-a». Using the traditional example of a square and a rectangle, a square «is-a» rectangle. By this, you should use subclassing for any situation where you feel a «is-a» is a meaningful relationship for your code. In your specific case of a subclass with nothing but a ...


0

In the example you gave, your partner is right. The two data helper builders are strategies. One is more specific than the other, but they are both interchangeable once initialized. Basically if a client of the datahelperbuilder was to receive the systemdatahelperbuilder, nothing would break. Another option would have been to have the ...


2

The most common use of such subclasses that I can think of is exception hierarchies, although that's a degenerate case where we would typically define nothing at all in the class, as long as the language lets us inherit constructors. We use inheritance to express that ReadError is a special case of IOError, and so on, but ReadError need not override any ...


0

I would use approach 2, putting it on the Comment model. I'd name the method something like loadAllCommentsForPost though, to clarify that it doesn't just load every single comment from the database. Though approach 1 wouldn't be too bad, consider that you might have a lot more models relating to Post later on. You wouldn't want your Post model cluttered ...


1

Let me first note that as the code is written, the sub-class is not actually more specific that the parent, as the two fields initialized are both settable by client code. An instance of the subclass can only be distinguished using a downcast. Now, if you have a design in which the DatabaseEngine and ConnectionString properties were reimplemented by the ...


1

I use constructor only subclasses quite regularly to express different concepts. For example, consider the following class: public class Outputter { private readonly IOutputMethod outputMethod; private readonly IDataMassager dataMassager; public Outputter(IOutputMethod outputMethod, IDataMassager dataMassager) { this.outputMethod = ...


9

If something is a pattern or an antipattern depends significantly on what language and environment you are writing in. For example, for loops are a pattern in assembly, C, and similar languages and an anti-pattern in lisp. Let me tell you a story of some code that I wrote long ago... It was in a language called LPC and implemented a framework for casting ...


1

I think the key to answering this question is to look at this one, particular usage scenario. Inheritance is used to enforce database configuration options, like the connection string. This is an anti pattern because the class is violating the Single Responsibility Principal --- It is configuring itself with a specific source of that configuration and not ...


1

A subtype is never "wrong" as long as you can always replace an instance of its supertype with an instance of the subtype and have everything still work correctly. This checks out as long as the subclass never tries to weaken any of the guarantees the supertype makes. It can make stronger (more specific) guarantees, so in that sense your coworker's intuition ...


49

If all you want to do is create class X with certain arguments, subclassing is an odd way of expressing that intent, because you aren't using any of the features that classes and inheritance give you. It's not really an anti-pattern, it's just strange and a bit pointless (unless you have some other reasons for it). A more natural way of expressing this ...


10

No, it's not an anti-pattern. I can think of a number of practical use cases for this: If you want to use compile time checking to make sure collections of objects only conform to one particular subclass. For example, if you have MySQLDao and SqliteDao in your system, but for some reason you want to make sure a collection only contains data from one ...


15

Which of these intuitions is correct? Your coworker is correct (assuming standard type systems). Think about it, classes represent possible legal values. If class A has one byte field F, you might be inclined to think that A has 256 legal values, but that intuition is incorrect. A is restricting "every permutation of values ever" to "must have field F ...


2

No, Chain of Responsibility doesn't make sense here, because it assumes all components have same interface. I don't think Java's type system is good enough to make this fully generic, so I would opt in to type erasure and some kind of "manager" that pipes output of one module into input of next one, while encapsulating the erasure. The module's interface ...


3

The connecting table that you speak of is called a junction table. Using the Wikipedia example, they have 3 tables defined. User ---- User ID User Login User Password User Name Permission ---------- Permission ID Permission Description UserPermission -------------- User ID Permission ID Now, you can map these 3 tables to PHP classes. It would probably ...


2

It's a violation of Liskov's substitution principle. Basically any class that uses SomeClass must be able to rely on the fact that addMember accepts a SomeClass or any of its subclasses. In your example, that's no longer true, because now you have an implementation of SomeClass that will cause a fatal error whenever a SomeClass object is passed that is not ...


1

The principle you're looking for is covariance and contravariance in type hints. To my knowledge, PHP doesn't support it.


1

I terms of readability and maintainability you will be better of with a dictionary if there are anything more than five or six actions. In terms of performance (depending on language, version, hardware etc. etc.) the trade off is:- Switch: one comparison per test value plus one branch per action if you assume the values are evenly distributed then you will ...


2

What if you have hundreds of values to choose from? How would your switch statement look like? Would it be maintainable? I think not. What you lose by using a map is very minimal hit in performance because of more misdirection - what you gain is huge, huge boost in maintainability. As mentioned by greyfade in the comments, you can also change the map ...


4

If you have an object oriented language, then it should be normal and expected that every value is an object; you need special justification if that is not the case. Update: it seems you're uncertain what the statement means, probably due to lack of contrast. So let me provide contrast: in other languages, even those which are considered OO languages, some ...


1

You're conflating multiple things when you over analyse the problem. For example, when designing a page object that reflects a real-world sheet of paper you start to consider pens. Don't! Take just the sheet of paper and consider its properties. It has a paper colour, texture, size. Then do not try to map your preconceptions of computing terms to the ...


1

Java takes the design philosophy that Undefined Behavior should not exist. Code such as: Cat felix = GetCat(); Woofer Rover = (Woofer)felix; Rover.woof(); will test whether felix holds a subtype of Cat that implements interface Woofer; if it does, it will perform the cast and invoke woof() and if it doesn't, it will throw an exception. The behavior of ...


3

You are handling errors across the boundary between two systems, effectively, so its best to think of the http handler as a system and the internal logic that throws these internal exceptions as a library. Given you want to catch these at the boundary point, and you do not want to map internal to external exceptions, then you're left with a simple catch-all ...


0

You can create reusable utility class that will resolve correct HttpException. try { securityService.login(credentials); } catch (InternalException e) { throw ExceptionUtil.resolveHttpException(e); } public class ExceptionUtil { public static HttpException resolveHttpException(InternalException exc) { if (exc instanceOf ...


11

Having one root object limits what you can do and what the compiler can do, without much payoff. A common root class makes it possible to create containers-of-anything and extract what they are with a dynamic_cast, but if you need containers-of-anything then something akin to boost::any can do it without a common root class. And boost::any also supports ...


1

Symbian C++ did in fact have a universal base class, CBase, for all objects that behaved in a particular way (mainly if they alloc'd heap). It provided a virtual destructor, zeroed the memory of the class on construction, and hid the copy constructor. The rationale behind was it was a language for embedded systems and C++ compilers and specs were really ...


2

Arguably "void" fulfils a lot of the roles of a universal base class. You can cast any pointer to a void*. You can then compare those pointers. You can static_cast back to the original class. However what you can't do with void which you can do with Object is use RTTI to figure out what type of object you really have. This is ultimately down to how not all ...


8

There are many good answers above, and the clear fact that anything you would do with a base-class-of-all-objects can be done better in other ways as shown by @ratchetfreak's answer and the comments on it is very important, but there is another reason, which is to avoid creating inheritance diamonds when multiple inheritance is used. If you had any ...


5

I'm going to suggest another reason that comes from Java. Because you can't create a base-class for everything at least not without a bunch of boiler-plate. You may be able get away with it for your own classes - but you'll probably find that you end up duplicating a lot of code. E.g. "I can't use std::vector here since it doesn't implement IObject - I'd ...


20

Because: You shouldn't pay for what you don't use. These functions make less sense in a value-based type system than in a reference-based type system. Implementing any sort of virtual function introduces a virtual-table, which requires per-object space overhead that is neither necessary nor desired in many (most?) situations. Implementing toString ...


5

In fact Microsofts early C++ compilers and libraries (I know about Visual C++, 16 bit) had such a class named CObject. However you have to know that at that time "templates" were not supported by this simple C++ compiler so classes like std::vector<class T> were not possible. Instead a "vector" implementation could only handle one type of class so ...


79

Because there are no functions shared by all objects. There's nothing to put in this interface that would make sense for all classes.


22

Whenever you build tall inheritance hierarchies of objects you tend to run into the problem of the Fragile Base Class (Wikipedia.). Having many small separate (distinct, isolated) inheritance hierarchies reduces the chances of running into this problem. Making all of your objects part of a single humongous inheritance hierarchy practically guarantees ...


51

Because what would that object have for functionality? In java all the Base class has is a toString, a hashCode equality and a monitor+condition variable. ToString is only useful for debugging. hashCode is only useful if you want to store it in a hash-based collection (the preference in C++ is for std::vector and plain unordered lists). equality without a ...


1

You're basically writing a compiler, which translates from SQL to whatever your datastore understands. In the end, you'll probably have the following parts: a Parser which takes SQL and produces an Abstract Syntax Tree a bunch of Visitors which do semantic analysis and/or rewriting on the AST an Interpreter which finally executes the (processed) query ...


0

Primarily Adapter to adapt native datastore commands to SQL dialect. IMHO I would advise you against exposing SQL API in such case. You are better off delivering native datastore-like commands (possibly wrapped somehow) that are supported by datastore developers. Simply - do you create costly overhead that won't deliver much value?


0

Firstly, congratulations on recognising that inheritance is a poor choice in this situation. You are 100% correct. Changing the type of an entity at run-time is definitely code smell! @Doc Brown's answer is getting to the heart of the matter, especially the comment about using Person rather than User, and allowing a 1:many between Person and roles. What is ...


0

You should keep an eye on two aspects here: The first one is how components you cannot change are already arranged. Third party components or some legacy components you don't want to change anymore Components you or your company wrote, which can be merged or split One of my Best Practices when deciding how to divide any code in packages is to let the ...


2

At our company, the dividing line between approach one and approach two comes down to the external dependencies of the component(s). For instance, we have hundreds of "core" components with no dependencies whatsoever, and those are grouped into only a single library. On the other hand, the one component that we use to talk to a specific type of database gets ...



Top 50 recent answers are included