I didn't take the usual CS route to learning programming and I often hear about namespaces but I don't really understand the concept. The descriptions I've found online are usually in the context of C which I'm not familiar with.
I am been doing Ruby for 2 years and I'm trying to get a deeper understanding of the language and OOP.
I am going to provide a more commonplace description.
Say my wife has a sister named Sue, and so do I. How can I tell them apart in a conversation? By using their last names ("Sue Larson" vs "Sue Jones"). The last name is the namespace.
This is a limited example of course, and in programming, the potential family members may be far more numerous than my example, therefore the potential for collisions is higher. Namespaces are also hierarchical in some languages (e.g. java), which is not paralleled with last names.
But otherwise it is a similar concept.
Definition of namespace from Wikipedia:
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers (i.e., names). ...
For example, one place you can find namespaces usable is something like this:
You define a constant or a variable, or even a class which has a generic name. If you don't wish to rename this constant/variable/class, but need to have another one with the same name, you can define that new instance in different namespace.
In ruby, a module is basically the same thing a namespace is in C++.
eg:
module Foo
BAZ = 1
end
module Bar
BAZ = 2
end
puts Foo::BAZ #=> 1
puts Bar::BAZ #=> 2
So, there, you have constant BAZ declared in two modules (aka namespaces in ruby)
A namespace provides a container to hold things like functions, classes and constants as a way to group them together logically and to help avoid conflicts with functions and classes with the same name that have been written by someone else.
In Ruby this is achieved using modules.
just think of it as a logical grouping of objects and functionality
Shortest answer: Namespaces create scope.
Wikipedia has a short but useful article on namespaces in general, as well as a much more detailed one for namespaces in computer science, with language-specific examples &c.
The key point is that, when you cannot "logically group" names into namespaces, i.e. you only have a single undifferentiated "spaces" where all names live, to avoid accidental clashes you end up clumsily re-implementing rudimental namespace functionality by such tricks as name prefixes &c. For example, "to draw" means something very different to an artist or to a gunslinger; if you couldn't have separate namespaces for artist-stuff and gunslinger-stuff, you'd end up with identifiers such as artist_draw and gunslinger_draw, and still risk accidental clashes if some library authors use different conventions, etc, etc.
From php.net:
What are namespaces? In the broadest
definition namespaces are a way of
encapsulating items. This can be seen
as an abstract concept in many places.
For example, in any operating system
directories serve to group related
files, and act as a namespace for the
files within them. As a concrete
example, the file foo.txt can exist in
both directory /home/greg and in
/home/other, but two copies of foo.txt
cannot co-exist in the same directory.
In addition, to access the foo.txt
file outside of the /home/greg
directory, we must prepend the
directory name to the file name using
the directory separator to get
/home/greg/foo.txt. This same
principle extends to namespaces in the
programming world.
So, as another poster mentioned, namespaces can be used to group items together.
To see why this might be useful, suppose you want to write a plug-in for, say, Wordpress, and you want to create a class named 'MyClass'. The trouble is, though, you have no idea if some other developer has already written another Wordpress plug-in using a class named 'MyClass'. So to avoid naming conflicts, instead you name your class 'MyPluginMyClass'. This is annoying, but it probably avoids naming conflicts.
But then comes the release of PHP 5.3, which finally supports namespaces (let's assume, too, that Wordpress and all of the servers on which it is deployed upgrade to PHP 5.3). Now you can create a namespace, say 'MyPlugin', and encapsulate 'MyClass' within it. Having done this, you can publish your plugin without worrying that your version of 'MyClass' will conflict with someone else's version of 'MyClass'.
Related
I have several schemas that inherit one or more elements from a collection of 'common' schemas. In this particular instance, I'm importing one of these schemas to make use of a single complex type defined in it.
When I generate the java objects from the schema, I get my schema types, and the element I referenced as expected, however I also get objects generated for the 30+ other types from the common schema.
I want to use the common schema, because I want to rely on automated builds for updating my schema when the common schema changes, but I do not want the extra java classes generated.
Suggestions ?
There's no out of the box approach to achieve what you want. The reason I am offering an opinion here is rather to point out (maybe for others) some issues one needs to take into account no matter which route ones go.
The 'extra' label is not always straightforward. Substitution group members are interesting. In Java, think about a class (A) using an interface (I), and a class (B:I) implementing (I). Some may say there's no dependency between A and B, while others would require B in the distribution. If you replace (I) with a concrete class, things become even less clear - consider that the substitution group head doesn't need to be abstract; or if the type of the substitution group head is anyType (Object in Java).
More so, if the XML processing was designed to accommodate xsi:type then it is even harder to tell (by looking at the schema) what is expected to work where.
Tools such as QTAssistant (I am associated with it) have a default setting that will pull in all strict dependencies (A and I above); and either ALL that might work (B above), or nothing else. Anything in between, the user needs to manually define what goes in the release. This is called automatic XSD refactoring and could be used easily in your scenario.
I'm quite new to Puppet, and so far I worked through the official tutorial, at least the introduction and part 1. So I guess I should have a basic understanding of how Puppet works and its terminology.
Anyway, there is one thing I don't get: In Puppet you have classes, which basically are nothing but outsourced manifests. So far, so good.
But why are they called class?
I have an OOP and CSS background, and I can also imagine the general concept of a class as a container for objects that have something in common. But none of these definitions match the concept of a class in Puppet. At least I don't get the analogy.
Can anybody bring some light into this?
PS: I know that there is no objective answer to this question, but primarily opinion-based, but I don't know where to ask elsewhere, so I hope for some advice :-)
You can relate Classes in puppet with division or separation of manifest bases on its role.
Classes are named blocks of Puppet code which are not applied unless they are invoked by name.
For the modularity and understanding of manifest it is recommended that different role of manifest code should be present in different file, which is called as classes.
And the name of class should denote its role. For example user(to create user), params(to pass parameters).
I believe it's recommended by Puppet and I'm sure it says this in the docs somewhere that you make classes for each of your node's roles that each contain requires for all other classes needed by that role with the same requires in multiple role classes if need be (which is allowed when you use the require command rather than include). This way you could have self contained classes such as 'fileserver' or 'webserver' which just need to be included in the node resources.
More on overlapping role classes:
http://docs.puppetlabs.com/puppet/2.7/reference/lang_classes.html#aside-history-the-future-and-best-practices
I would like to have one or more libraries of reusable classes that are basically value objects, such as Address, PhoneNumber, EmailAdress, containing mostly properties and a few supporting methods. How can my Domain layer use these without breaking the rule that the Domain Layer should not contain external references, and without defining them as interfaces/abstract classes in the Domain Layer?
... without breaking the rule that the Domain Layer should not contain external references
I think your definition of 'external references' requires some reevaluation. It is hard to imagine a domain layer that does not reference anything. In C# and Java you will reference at least basic numeric types, dates and strings. I also don't see any harm in referencing external libraries like Noda/Joda time. On the other hand, you of course would not want to reference any heavy technical libraries like persistence, communication, UI etc.
So I would say that you can build your own reusable library referenced from domain but it requires a very careful consideration, and is often not worth the coupling that it will create. I would use a following criteria for every type:
Should be context-independent. EmailAddress for example is relatively independent of the context it is used from. Address on the other hand may have a different meaning depending on a Bounded context.
Should be stable (does not change often).
Should not hide any out-of-process communication (db, network etc)
Should not have any dependencies of its own (other than standard Java/C#)
I think that what you're referring to is a shared kernel.
Shared Kernel – This is where two teams share some subset of the
domain model. This shouldn’t be changed without the other team being
consulted.
While this looks great at first, since we are drilled not to repeat ourselves, be aware of the pitfalls:
The concepts should have the same meaning in every context. Some of these concepts hold subtle nuances depending on the context. Ask your domain expert.
Changes are more expensive; it might be cheaper to duplicate these few classes so that you can change them on your own than to have to consult multiple teams when something changes.
Stability cuts both ways. If you pull an entity out into each domain, then any changes have to be executed across multiple projects. If you don't, then changes have to be coordinated across multiple domains. The logistics of the former are easier than the latter, but the work involved in the latter can be greater. Either way, you have to test the changes on each platform.
And unless the entity is mature with a relatively well-defined semantics, my experience is that almost everything changes. So stability is nice, but might be a bit of a red herring.
That being said, I like (and +1) #Dmitry.
For example let's say we have a class called "Secretary" and another class called "Utils"
Utils has some functions that do general stuff, for example finding the maximum of 3 integers.
"Secretary" needs to call some of these functions and in this class these functions are called using the following notation:
Utils.function()
now my question is, what kind of association, if there is any, exists between these two classes?
Most likely Dependency. Associations are normally used to capture some relationship that has meaningful semantics in a domain. So, for example, Secretary 'works for' Manager. Your example is different: you're not capturing meaningful relationships among instances. Therefore Dependency is probably most appropriate.
More importantly though: what are you trying to illustrate? Remember to use UML like any other tool - make it work for you. So, for example, it's fine to show a binary association if (a) it helps you and/or (b) it helps you communicate with other team members. The fact that it doesn't comply with the intended UML usage doesn't matter - as long as you find it useful.
hth.
Coming up with good, precise names for classes is notoriously difficult. Done right, it makes code more self-documenting and provides a vocabulary for reasoning about code at a higher level of abstraction.
Classes which implement a particular design pattern might be given a name based on the well known pattern name (e.g. FooFactory, FooFacade), and classes which directly model domain concepts can take their names from the problem domain, but what about other classes? Is there anything like a programmer's thesaurus that I can turn to when I'm lacking inspiration, and want to avoid using generic class names (like FooHandler, FooProcessor, FooUtils, and FooManager)?
I'll cite some passages from Implementation Patterns by Kent Beck:
Simple Superclass Name
"[...] The names should be short and punchy.
However, to make the names precise
sometimes seems to require several
words. A way out of this dilemma is
picking a strong metaphor for the
computation. With a metaphor in mind,
even single words bring with them a
rich web of associations, connections,
and implications. For example, in the
HotDraw drawing framework, my first
name for an object in a drawing was
DrawingObject. Ward Cunningham came
along with the typography metaphor: a
drawing is like a printed, laid-out
page. Graphical items on a page are
figures, so the class became Figure.
In the context of the metaphor, Figure
is simultaneously shorter, richer, and
more precise than DrawingObject."
Qualified Subclass Name
"The names of subclasses have two jobs.
They need to communicate what class
they are like and how they are
different. [...] Unlike the names at
the roots of hierarchies, subclass
names aren’t used nearly as often in
conversation, so they can be
expressive at the cost of being
concise. [...]
Give subclasses that serve as the
roots of hierarchies their own simple
names. For example, HotDraw has a
class Handle which presents figure-
editing operations when a figure is
selected. It is called, simply, Handle
in spite of extending Figure. There is
a whole family of handles and they
most appropriately have names like
StretchyHandle and TransparencyHandle.
Because Handle is the root of its own
hierarchy, it deserves a simple
superclass name more than a qualified
subclass name.
Another wrinkle in
subclass naming is multiple-level
hierarchies. [...] Rather than blindly
prepend the modifiers to the immediate
superclass, think about the name from
the reader’s perspective. What class
does he need to know this class is
like? Use that superclass as the basis
for the subclass name."
Interface
Two styles of naming interfaces depend on how you are thinking of the interfaces.
Interfaces as classes without implementations should be named as if they were classes
(Simple Superclass Name, Qualified Subclass Name). One problem with this style of
naming is that the good names are used up before you get to naming classes. An
interface called File needs an implementation class called something like
ActualFile, ConcreteFile, or (yuck!) FileImpl (both a suffix and an
abbreviation). In general, communicating whether one is dealing with a concrete or
abstract object is important, whether the abstract object is implemented as an
interface or a superclass is less important. Deferring the distinction between
interfaces and superclasses is well >supported by this style of naming, leaving you
free to change your mind later if that >becomes necessary.
Sometimes, naming concrete classes simply is more important to communication than
hiding the use of interfaces. In this case, prefix interface names with “I”. If the
interface is called IFile, the class can be simply called File.
For more detailed discussion, buy the book! It's worth it! :)
Always go for MyClassA, MyClassB - It allows for a nice alpha sort..
I'm kidding!
This is a good question, and something I experienced not too long ago. I was reorganising my codebase at work and was having problems of where to put what, and what to call it..
The real problem?
I had classes doing too much. If you try to adhere to the single responsibility principle it will make everything all come together much nicer.. Rather than one monolithic PrintHandler class, you could break it down into PageHandler , PageFormatter (and so on) and then have a master Printer class which brings it all together.
In my re-org, it took me time, but I ended up binning a lot of duplicate code, got my codebase much more logical and learned a hell of a lot when it comes to thinking before throwing an extra method in a class :D
I would not however recommend putting things like pattern names into the class name. The classes interface should make that obvious (like hiding the constructor for a singleton). There is nothing wrong with the generic name, if the class is serving a generic purpose.
Good luck!
Josh Bloch's excellent talk about good API design has a few good bits of advice:
Classes should do one thing and do it well.
If a class is hard to name or explain then it's probably not following the advice in the previous bullet point.
A class name should instantly communicate what the class is.
Good names drive good designs.
If your problem is what to name exposed internal classes, maybe you should consolidate them into a larger class.
If your problem is naming a class that is doing a lot of different stuff, you should consider breaking it into multiple classes.
If that's good advice for a public API then it can't hurt for any other class.
If you're stuck with a name, sometimes just giving it any half-sensible name with commitment to revising it later is a good strategy.
Don't get naming paralysis. Yes, names are very important but they're not important enough to waste huge amounts of time on. If you can't think up a good name in 10 minutes, move on.
If a good name doesn't spring to mind, I would probably question whether there is a deeper problem - is the class serving a good purpose? If it is, naming it should be pretty straightforward.
If your "FooProcessor" really does process foos, then don't be reluctant to give it that name just because you already have a BarProcessor, BazProcessor, etc. When in doubt, obvious is best. The other developers who have to read your code may not be using the same thesaurus you are.
That said, more specificity wouldn't hurt for this particular example. "Process" is a pretty broad word. Is it really a "FooUpdateProcessor" (which might become "FooUpdater"), for example? You don't have to get too "creative" about the naming, but if you wrote the code you probably have a fairly good idea of what it does and doesn't do.
Finally, remember that the bare class name isn't all that you and the readers of your code have to go on - there are usually namespaces in play as well. Those can often give readers enough context to see clearly what your class if really for, even if its bare name is fairly generic.