Related
Here's a somewhat general computer question. I've always been able to follow the LOGIC of programming, but when I go to code something, I always find that I don't know some method or another to get what I need to get done. When I see it, I always think, "OF COURSE!".
How do you go about finding relevant methods for your programming needs that are "built-in?" I don't enjoy re-inventing the wheel, but I find it difficult to find what I need to do what I want to do.
First try Google:
You can use google to search your required method. For example If I want to search a value in array in PHP then I go to Google and type "Search values in array in PHP". I find my required function at first place.
Then try Standard Documentation:
Try standard documentation to search for your required method. For example if my problem is related to strings in PHP then I go to String Functions documentation and find the required function.
Finally try Stackoverflow:
Otherwise you can ask your problem at Stackoverflow for your required methods and libraries. You will always get a shortest way.
What you are asking here is for the best way to do research. Well, that's hard skill to explain, even more so to teach.
Nevertheless here are some tips:
Go to a search engine. It makes no
sense to start in a place like MSDN,
since all of its content is indexed
by the search engines anyway.
Phrase your question several
different ways.
As you learn more
about the issue you will learn new
vocabulary about it. Use that new
vocabulary to do even more searches.
If the searches turn out empty,
switch to browsing a specific
section of the official
documentation that you think is the
most related to what you are doing. If nothing else, it will expand your horizons around the issue and give you more vocabulary to do more searches.
Finally, if all else fails ask a question on StackOverflow explaining what you want to do as clearly as possible.
Note that if there's a simple API that does what you need, you will rarely reach step 4.
You say:
It's very frustrating to suddenly find
an "easy" button mid-way through.
Try to see it differently. Think of these moments as blessings. You've just learned something. You invested a lot of effort - and instead of seeing that effort as wasted, see it as critical to proper learning. You - better than the guy who just happened across the magic method - really understand what it's for and something about how it works. And you really, really, understand why you need it, and you properly appreciate its value. You're never going to forget that method.
So it was costly, but you learned something important. Celebrate, and move on.
It is usually included in some form of documentation. Most IDEs support the documentation format and gives you auto-complete functionality.
if you are using MVS so MSDN is really good for it
In addition to this and this answer above, google's basic and advanced searching tips prove very helpful.
In addition to above, changing the order of keywords in search criteria also sorts the list in different orders.
In essence I believe that searching is still an art rather than a science, and is best learnt - quoting from David Reis' answer above: "2. As you learn more about the issue you will learn new vocabulary about it. Use that new vocabulary to do even more searches."
Search in the API documentation. But the best way to (I found so) is to search on the internet for multiple solutions and then choose the one that you think is best. Make your search as narrow as possible. For example you want to implement random number generation function, then search like this, "How to generate random numbers in Java?".
Namespaces, namingconventions, Autocomplete/Intellisence
I assume that you are trying to find some kind of Object-Oriented-apis . I use .net in my example.
First try to find a class that might be responsable for the method you are looking for.
Example: If you want to "Make a new Directory in the Filesystem" you must know (or learn) that (in dotnet) these classes are in the namespace System.IO:
This namespace contains subnamespaces like Compresseion and Classes like File, Path, Directory, ...
Second you sould know NamingConventions. There are common Naming-Prefixes for methods like Get, Set, Insert, Create. In the documentation for class Directory you will find a CreateDirectory-Method.
If you have an intelligent editor that knows your programming language and the classes and namespaces learning is much easier. In the dotnet-world this feature is called Autocomplete/Intellisence
In other words - what would be a good name for a variable that references the currently logged user?
I've come up with a few:
logged_user
visitor
me
I'm not convinced either of them is good enough though.
current_user seems the obvious choice.
The underlying point is worth some elaboration.
It is very important to choose good variable names, where a "good name" has the properties of being
accurate (not sloppily named)
concise (short as possible, without losing meaning)
unambiguous (not easily confused for something else)
If you are stuck then try to describe the thing in plain English.
Do you want to store the name of the user who is currently logged in? How about currentlyLoggedInUser?
In your context do you care about users not logged in?
If not then currentUser would do fine, and it's more concise.
Can it be confused for something else?
Nope. We have a winner!
Now you could shorten it further, like currUser but you lose some of the clarity. Remember the IDE will be there to help you type, so you have to think what you're losing (clarity) as a trade off from what you gain (fewer keystrokes). That point can be settled by personal taste when you're developing by and for yourself, but if you're in a team it's a no-brainer; choose the version that will be easiest to understand in future.
Think of that axe-wielding maniac who has to maintain your code in five years time.
Either theUserWhoLoggedInAFewMinutesBeforeAndWhoHasNotYetLoggedOutAgain or just ich
authenticatedUser, validUser, activeUser, authUser
I would be more inclined to go with the simplest form user. If you need to identify a previously logged on user then previousUser is a logical choice. Also, if you need to distinguish between a user that is logged in or not then a simple isUserLoggedIn boolean will do the trick.
loggedOnUser seems appropriate.
I think currentUser OR loggedInUser seems better.
Routines, procedures, methods - whatever you call them, they are important building blocks for us developers. What single characteristic would you rate as the most important one?
(By providing one characteristic per answer, it is possible to vote for them individually. I.e. the purpose of this question is not to decide single out one characteristic, but rather, to highlight all of the important ones.)
I think the most important criteria would be that it has a single purpose.
After that, that it satisfies that purpose (and only that purpose) correctly.
Self Commenting Procedure Names.
Examples:
GetStoreFromAddress
GetCarsByMake
It should be easily unit tested.
The routine's name maps one to one to it's functionality.
It's surprising how often a function X does X and also Y, or most of X but not all of X.
There is no single criterion that distinguishes a good routine from a bad one.
Among the criteria are:
conceptual integrity: it does
something that can be described in a
simple short form, one sentence or
paragraph;
loose coupling: its behavior is not
sensitive to what goes on in code
around it;
reasonable size: long routines are
harder to read and understand, and
are less likely to have good
conceptual integrity;
Parnas's criterion: they "hide"
one thing that can change, so that
requirements changes have limited
effect on the rest of the system.
designed to be easily read and understood by humans - without that in place it is much harder to modify it to have all of the other wonderful attributes that will be listed here
Number of things it tries to do.
If this isn't exactly 1 then you probably have a problem.
It shouldn't have unexpected side-effects.
good error handling (reliability)
brevity
(this was supposed to be a semi-fun answer, but SO wouldn't let be post the single word on its own!)
It has to be atomic
Lines of code.
You should track the number of edits required after the routine was put into use. A 'good' routine is one with few edits required. A 'bad' routine definitely proves itself to be so when there are a bunch of fixes required.
This can easily be accomplished with a comment header on each method call that gets updated after each edit.
It does one thing or delegates multiple things to other functions
Clarity - Easy to understand
I think this is more easily answered if you consider routines as part of an API. There aren't many routines that stand alone, at least not in a truly useful system. So honestly, I think the most important things to consider when writing routines are:
Intuitiveness How intuitive is my set of instructions -- will people understand the purpose without having to wade through a lot of documentation?
Orthogonality How orthogonal are my routines? Does each accomplish one particular task, or are there multiple (but slightly different) ways to do the same thing? If there are, this is bad, and the API probably needs to be redesigned.
Compactness How much of the API does it take to get simple tasks done? Do I need to learn a lot of stuff to get something done, or can I suffice with just a couple routines that do something intuitive and powerful? You need to weigh the tradeoffs of this one with orthogonality to strike a good balance for your particular domain.
From the routine name, you can say what the routine does (and when you check the code, you realize that you were right ;-)
The routine uses a consistent level of abstraction throughout.
I would say well documented (and actually enforced) pre and post conditions.
A single return point
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm currently developing a PHP application that's using an Access database as a backend. Not by choice you understand... the database is what the client used originally and using it is part of the requirements.
One of the problems with this database is that the column names have the most insane naming convention you could possibly imagine. Uppercase, lowercase, underscores, spaces and the plain insane. For example the column "gender" holds a date. And so does column "User2". There's a lot more but you get the idea.
Faced with this I decided to create an array to map the database columns to PHP variables so we can isolate the code from the madness. However my colleague believes that I'm over-complicating things and we should use the database's column names for the corresponding PHP variables so we don't need to go through the mapping array to find what goes where.
So my question is this... am I doing the right thing or am I complicating things?
Absolutely you are on the right track. If you don't abstract away the madness you will eventually succumb to the madness yourself.
Your colleague has a valid point though, so I suggest you also code an easy way to determine the data to column mapping in PHP.
This isn't about keeping it simple, it's about retrofitting a solid foundation to build upon.
The thing that would worry me is that this kind of random design often hides certain business rules, things like "...if the gender is a date then they must have purchased a widget at some point therefore they can't be allowed to fribbish the lubdub... " - crazy I know but more common than it should be.
Names are exceptionally important. If you want your application to be maintainable, fix them before the code base grows further.
I wouldn't say you are complicating things.
Eric Evan's book Domain Driven Design has a lovely term for this: Anti Corruption Layer
To play Devil's Advocate, there's something to be said for not having an unnecessary layer of indirection in your short-term memory load for working with the system. Once familiar with the code, you will know what goes in which variable, so the main benefit is to someone new picking up the code from scratch. However, fixing that problem properly would also require fixing up the database schema which would (a) be a significant body of work, and (b) largely make the problem go away.
There is no black-and-white answer to this question, and the lack of an obvious answer to your specific problem suggests that you may want to let sleeping dogs lie.
On the other hand, if a cleanup operation is within the bounds of possibility then you may want to do it on a re-factoring type basis, incrementally fixing up the DB column names as the opportunity arises.
Just create views where it is most needed.
This is a good question as it talks to the heart of coding IMHO.
I would go with you and abstract out the bad names into readable decent names. The result being a little complication for much more logically understandable and readable code.
You didn't say you can't rename the columns in Access, so....do that! Another possibility would be to create views for each table, and rename the columns in the view. Then instead of working with table Employees, you work with view vEmployees. If I recall correctly, Access lets you update views as well as select from them. If you are using an ORM with PHP, that may not support updating views however.
Hard coding table names and column names is never a good idea even when the names make sense.
I don't know if using arrays is the best solution though. I'm not really familiar with PHP but I would have gone with something like constant strings to store the table names. In the languages I work in this would lead to more readable code.
You are very unlucky to be stuck with this database but I think on the whole a way of abstracting the field names into something more sensible is smarter.
I would perhaps create a data structure containing the database name, sanitised name, type and a field for the content when you're pulling the data out of the DB. That would give a convenient way of drawing things together so you're not only mapping away the crazy name scheme.
Absolutely you're doing the right thing. In my opinion it's better to implement some sanity there. Going forward, you're logic wouldn't be throw away if they decided to change that database or any of it's column names. If you build your mapping the right way, it should be easy to just plug the new tables/columns right in.
If anything, what you're doing improves the agility of your overall solution.
Of course I would still say KISS applies to the method of your mapping!
Using proper column names in your end of the application is the best you can do. And you should do it unless you want to have to look up "what that field was supposed to be again?" when you have to look at it again after you did something else.
Your colleague's point is not to overcomplicate things. That's valid, too.
So encapsulate access to the fields in a method or methods and have that method do the translation. Using maps this shouldn't be a performance problem.
In fact putting all the mapping to the data source in one object might help you if your customer reconsiders to use a real database. And customers love to change their opinion.
Why not create a datalayer with classes that map on to each table. Then you can define the class methods to access the columns and give the methods whatever names you want. Then the datalayer database access code is the only thing that needs to know about the real column names. I suspect that someone (perhaps several soneones) has already developed a framework to do this. Google "php orm".
Use a ORM, you will be changing the db soon...
You still need to maintain database. One possible approach I can suggest is to map field names in application code as you plan it to do. But then sooner or later you have to start handling this naming madness with field names and fix it. It is not good idea just to screen from a problem and imagine that it is a safe solution and good way to go. It is only temporary workaround. Do not full your self about it.
What is the best way to sort class members?
I'm in conflict with a team member about this. He suggests that we should sort the members alphabetically. I think it's better to organize in a semantic manner: important attributes first, related methods together, etc.
What do you think?
I like semantic. Alphabetical doesn't seem to make a lot of sense to me, cause when you're looking for a member, you rarely know exactly what it's called. Also, if you're using any sort of naming convention (eg: Hungarian), alphabetical is going to lead to grouping by type, which may not be what you want.
Group related class members together. I think this will help other programmers understand your interface more easily when they see it for the first time.
Some also find it helpful to organize accessors and modifiers together in separate sections.
I've studied this exact issue as part of my master's thesis.
An alphabetical organization or organization based on public/private is better for being able to find specific things. However, in some IDEs you can set the outline tool to sort alphabetically and to use special indicators for public/private.
My approach was to group methods based on what members they use: there is often a conceptual connection between methods that use the same fields.
I actually created a visualization from that, which helped to quickly navigate and understand the structure of huge classes.
I never look for a member by going through the code. When I want to jump to a member definition, I either select it from the navigation bar / document outline / class view, or I right-click and select "Jump to definition". You don't need to sort the members if you have a decent IDE. This works very good in Visual Studio and the other IDE I use if needed, KDevelop, supports at least the basics of this.
Anyway, I tend to group members by functionality, i.e. all fields / properties / methods that are part of some specific functionality are together. And since classes shouldn't be too long, this is enough.
This is just my opinion, which I am sure will be unpopular, but the problem with semantic sorting is its subjective. Each person will have a different opinion of what methods should be close together.
Alphabetical has the advantage that it is entirely objective. It also reduces large diffs for small changes, which is common when one coder chooses a different semantic ordering.
Most IDEs have outlines, or hyperlinks to make navigation easier.
EDIT: A clarification- I still sort by public first to private, but alphabetical within the same access level. In fact, I don't do any sorting - I let my IDE resort the file for me when saving.
Are you writing a phone book?
With a semantic approach you can easily show what are the most important methods.
I generally go with Constructor, Destructor first, then important methods followed by getters and setters and eventually misc. methods. Finally, I take a similar approach for internal parts (private methods, attributes...).
Alphabetical order does not convey any useful information about your class. If you really want to see methods sorted alphabetically, you should rely on a function of your IDE.
You can go from semantic to alphabetic by sorting the "methods display" in your IDE.
You can't go (automatically) from alphabetic to semantic.
Hence: semantic.
Assuming you are using a modern IDE, finding the method you want is rarely more than two mouse clicks away, so I am not sure what having a particular way of organizing your methods would get you. I do use stylecop (http://code.msdn.microsoft.com/sourceanalysis) which has me ordering by public / private / method / properties - I have found that to be anal enough.
The only time I ever truely thought this was important is when I wrote a very large jscript program and the editor at the time didn't offer any help in finding functions. Alphabetic organization was very helpful. When alphabatized, it isn't hard to figure out which way in the file you need to go to find a method. Semantic organization would have been completely unhelpful.
At a higher level, I would organize my class this way:
Constructor
Destructor
Private Fields
Properties
Methods/Functions
Then for methods/functions I would break it down again by functionality. e.g. I would put methods that implement an interface into one region, I would put event handlers methods into one region, etc...
RWendi
I guess I'm one of the oddball cases who favors alphabetical listings.
First and foremost, it's been my experience that grouping methods together "semantically" tends to be a time-sink. Now, if we're talking about grouping them by scope/visibility, that's another thing. But then, if the member changes it's scope, you have to sink time into moving the member to keep the code current. I don't want to have to waste time shuffling code around to observe a guideline like that.
I am also not a big fan of regions. When properties and methods are grouped by scope, they tend to shout out for enclosure in a region. But enclosing code in collapsing regions tends to hide badly written code. As long as you don't have to look at it, you won't be bothered to think about refactoring it to make it maintainable.
So, I favor alphabetical organization. It's simple, direct, and to the point. I'm not tempted to enclose groups into regions. And since the IDE makes it easy to leap to a function or property definition anyway, the physical layout of the code is moot. It used to be that you wanted folks to focus on your public members first. Modern IDEs make that largely a pointless argument in favor of scope-based layouts.
But the biggest advantage of alphabetical layouts is this: printed code samples during code reviews. And I use them alot. It makes finding a function or a property a snap. If you've ever had to wade through a lot of code to find a function or a property when things weren't just alphabetically listed, you'll know what I'm talking about.
But, as they say, those are my subjective views on the subject. Your mileage may vary.